frontcontroller.java

来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 71 行

JAVA
71
字号
package forum;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * An implementation of the front controller pattern, using the command
 * and controller strategy.
 *
 * @author    Simon Brown
 */
public class FrontController extends HttpServlet {

  /**
   * Processes the request - this is delegated to from doGet and doPost.
   *
   * @param req   the HttpServletRequest instance
   * @param res   the HttpServletResponse instance
   */
  protected void processRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

    System.out.println("------------------------------------");
    System.out.println("FrontController : Processing request");

    // find which action should be used
    String actionName = req.getPathInfo().substring(1);
    System.out.println("FrontController : Action name from request is " + actionName);

    // use the helper class to locate the action
    Action action = ActionHelper.getAction(actionName);
    System.out.println("FrontController : Action class to process request is " +
      action.getClass().getName());

    // now process action, finding out which view to show the user next
    String nextView = action.process(req, res);
    System.out.println("FrontController : Next view is " + nextView);
    System.out.println("------------------------------------");

    // and finally redirect to appropriate view
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextView);
    dispatcher.forward(req, res);
  }

  /**
   * A default implementation of doGet that delegates to the processRequest method.
   *
   * @param req   the HttpServletRequest instance
   * @param res   the HttpServletResponse instance
   */
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

    processRequest(req, res);
  }

  /**
   * A default implementation of doPost that delegates to the processRequest method.
   *
   * @param req   the HttpServletRequest instance
   * @param res   the HttpServletResponse instance
   */
  protected void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

    processRequest(req, res);
  }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?