FileDocCategorySizeDatePackage
FrontController.javaAPI DocExample2848Sat Nov 22 19:35:12 GMT 2003s2wexample.controller

FrontController

public class FrontController extends HttpServlet
A front controller that uses dispatchers to determine what pages to forward to.

Fields Summary
private static final String
DISPATCHER_ATTR
the session attribute for the current dispatcher
private static final String
DISPATCHER_PREFIX
the class prefix for dispatcher classes
Constructors Summary
Methods Summary
public voiddoGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
Handle GET requests by forwarding to a common method

    
                  
         
       
        process(request, response);
    
public voiddoPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
Handle POST requests by forwarding to a common method

        process(request, response);
    
protected voidprocess(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
Process a request by forwarding to the appropriate dispatcher

        HttpSession session = request.getSession();
        ServletContext context = getServletContext();
        
        // get the last element of the request in lower case
        String reqPath = request.getPathInfo();
        reqPath = Character.toUpperCase(reqPath.charAt(1)) +
                                        reqPath.substring(2).toLowerCase();
        
        // find the dispatcher in the session    
        Dispatcher dispatcher =
            (Dispatcher) session.getAttribute(reqPath + DISPATCHER_ATTR);
        
        // if no dispatcher was found, create one
        if (dispatcher == null) {
            String className = reqPath + "Dispatcher";
            try {
                Class c = Class.forName(DISPATCHER_PREFIX + className);
                dispatcher = (Dispatcher)c.newInstance();
            } catch (Exception ex) {
                throw new ServletException("Can't find class " + className, ex); 
            }
            
            dispatcher.setContext(context);
            session.setAttribute(reqPath + DISPATCHER_ATTR, dispatcher);
        }
        
        // make sure we don't cache dynamic data
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        
        // use the dispatcher to find the next page
        String nextPage = dispatcher.getNextPage(request);
        
        // forward control to the view
        RequestDispatcher forwarder = request.getRequestDispatcher("/" + nextPage);
        forwarder.forward(request, response);