001// Copyright 2008 by Basil Vandegriend.  All rights reserved.
002
003package com.basilv.examples.annotations;
004
005import java.io.IOException;
006import java.lang.reflect.Method;
007
008import javax.servlet.*;
009import javax.servlet.http.*;
010
011public class DispatchingServlet extends HttpServlet
012{
013  @Override 
014  protected void doGet(HttpServletRequest request,
015    HttpServletResponse response) throws ServletException,
016    IOException {
017    response.setContentType("text/html;charset=UTF-8");
018
019    String url = request.getPathInfo();
020    ActionExecutor executor = new ActionExecutor(request,
021      response);
022
023    boolean actionFound = false;
024    for (Method method : ActionExecutor.class.getMethods()) {
025      if (method.isAnnotationPresent(WebAction.class)) {
026        WebAction action = method.getAnnotation(
027          WebAction.class);
028        if (url.equals(action.url())) {
029          actionFound = true;
030          try {
031            method.invoke(executor, (Object[]) null);
032          } catch (Exception e) {
033            throw new RuntimeException(
034              "Error invoking method [" + method.getName()
035                + "].", e);
036          }
037        }
038      }
039    }
040    if (!actionFound) {
041      request.setAttribute("message", "No action found");
042    }
043    RequestDispatcher rd = request
044      .getRequestDispatcher("/view.jsp");
045    rd.forward(request, response);
046  }
047
048  @Override 
049  protected void doPost(HttpServletRequest request,
050    HttpServletResponse response) throws ServletException,
051    IOException {
052    doGet(request, response);
053  }
054}