⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 controllerservlet.java

📁 Oracle的J2EE Sample
💻 JAVA
字号:
/*
 * @author : Umesh Kulkarni
 * @version 1.0
 *
 * Development Environment : Oracle9i JDeveloper
 * Name of the File        : ControllerServlet.java
 * Creation / Modification History
 *    Umesh           26-Apr-2002        Created
 *
 */
package oracle.otnsamples.ibfbs.control;

// Import Required Packages
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.util.HashMap;
import java.net.MalformedURLException;
import oracle.otnsamples.ibfbs.utils.XMLUtils;

/**
 * This Servlet Class acts as a Controller Servlet for this entire application.
 *
 * In a typical MVC (Model-View-Controller) Architecture, the Controller Component
 * takes the responsibility of controlling the entire execution flow.
 * The View Layer, assumes the responsibility of representing the data whereas
 * the Model Layer is responsible for implementing the Business Logic.
 *
 * This controller layer takes the help of RequestProcessor to process the requests.
 * This controller layer also takes the help of ViewManager to get the next appropriate
 * view to be used.
 *
 * In a typical web application, there exists various events in the form of
 * button clicks, combo box selections etc.
 *
 * In response to these events, application executes the functionality embedded in
 * some methods in some classes. The relationship between various events and corresponding
 * methods, corresponding classes is captured in Control.xml file.
 *
 * @version 1.0
 * @since 1.0
 */
public class ControllerServlet extends HttpServlet {

  /**
   * Method which is invoked by the Servlet Engine when the Servlet is initialized.
   *
   * @param config Servlet Configuration Object see javax.servlet.ServletConfig
   * @exception ServletException Exception raised when Servlet Engine tries to initialize
   *                            this Servlet.
   * @since 1.0
   */
  public void init(ServletConfig config) throws ServletException {

    super.init(config);

    try {

      // Get the Control XML File capturing relationship between various events
      // and corresponding class names, method names etc
      String ctrlMapFile =
        config.getServletContext().getResource("/WEB-INF/xml/Control.xml")
          .toString();

      // Get the Exception XML file which captures the relationship between various
      // exception classes and associated JSP page to display the exception messages.
      String excpMapFile =
        config.getServletContext().getResource("/WEB-INF/xml/Exception.xml")
          .toString();

      // Parse the Control XML File and get the relasionship as a set of URLMapping Classes
      HashMap urlMap = XMLUtils.parseControlFile(ctrlMapFile);

      // Set this as attribute of the context so that it is accessible from anywhere
      getServletContext().setAttribute(FBSKeys.URLMAPPINGS, urlMap);

      // Parse the Exception XML File and get the set of ExceptionMapping Classes
      HashMap exceptionMap = XMLUtils.parseExceptionFile(excpMapFile);

      // Set this as attribute of the context so that it is accessible from anywhere
      getServletContext().setAttribute(FBSKeys.EXCEPTIONMAPPINGS,
                                       exceptionMap);

    } catch (MalformedURLException mx) {  // Trap Errors When Formed URL is not valid
      System.out.println("Error initializing mappings " + mx);
    } catch (Exception ex) {  // Trap Other Errors
      System.out.println("Error : " + ex.toString());
    }

    // Initialize Request Processor and View Manager
    getRequestProcessor();
    getViewManager();
  }

  /**
   * Method to process any request. Request processing of all the events raised in
   * this application happens through this method. This method is the most important
   * method of the controller servlet.
   *
   * @param request Request Object of the Servlet
   * @param response Response Object of the Servlet
   * @exception ServletException
   * @exception IOException
   *
   * @since 1.0
   */
  public void process(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {

    String nextScreen;
    try {

      // Get the Class handling Request Processing Functionality
      RequestProcessor rp = getRequestProcessor();

      // Process the Request. If any errors are raised during processing
      // this request, control goes to the catch section.
      rp.processRequest(request);

      // Get the Next Screen for this Request
      nextScreen = getViewManager().nextScreen(request,"EVENTNAME");

      // Set Header for Preventing Caching of Pages
      setHeader(response);
      // Remove the attribute as no error occured.
      // This atribute is used only when some error occurs.
      request.getSession(true).removeAttribute("CALLOUT_EVENT");

    } catch (Throwable ex) {  // Catch Any Error
      String className = ex.getClass().getName();
      if (request.getSession(true).getAttribute("CALLOUT_EVENT") == null) {
        request.getSession(true).setAttribute("CALLOUT_EVENT",request.getParameter("CALLOUT_EVENT"));
      }

      // Get the name of the Error Page to Display the Error Message
      nextScreen = getViewManager().nextErrorScreen(ex, request);

      // put the exception in the request
      request.setAttribute("javax.servlet.jsp.jspException", ex);
      request.setAttribute("ErrorMessage",ex.toString());

      if (nextScreen == null) {

        // send to general error screen
        ex.printStackTrace();

        throw new ServletException("MainServlet: unknown exception: "
                                   + className);
      }
    }

    // Forward the control to the appropriate view.
    getServletConfig().getServletContext().getRequestDispatcher(nextScreen)
      .forward(request, response);
  }

  /**
   * Method which gets invoked when the Servlet receives HTTP GET Request.
   *
   * @param request Request Object of the Servlet
   * @param response Response Object of the Servlet
   * @exception ServletException
   * @exception IOException
   *
   * @since 1.0
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {

    // Process the request
    process(request, response);
  }

  /**
   * Method which gets invoked when the Servlet receives HTTP POST Request.
   *
   * @param request Request Object of the Servlet
   * @param response Response Object of the Servlet
   * @exception ServletException
   * @exception IOException
   *
   * @since 1.0
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    // Invoke doGet Method to process this request
    doGet(request,response);
  }

  /**
   * Method to get the Request Processor Class. This Class handles all the request
   * processing for a typical event. The request processing includes instantiating
   * a business class and invoking a particular method.
   *
   * @return Instance of Request Processor
   * @since 1.0
   */
  private RequestProcessor getRequestProcessor() {

    // Try to get the Request Processor from the Servlet Context
    RequestProcessor rp =
      (RequestProcessor) getServletContext()
        .getAttribute(FBSKeys.REQUESTPROCESSOR);

    // If this is the first request, then this attribute is not set and hence
    // we need to instantiate a new instance.
    if (rp == null) {

      // Create a new instance and initialize it.
      rp = new RequestProcessor();

      rp.init(getServletContext());

      // Put this instance as attribute of Servlet Context
      getServletContext().setAttribute(FBSKeys.REQUESTPROCESSOR, rp);
    }

    return rp;
  }

  /**
   * Method to get the View Manager Class. This Class handles all the view
   * management for a typical event. The view Management typically includes finding
   * a typical view to represent the data.
   *
   * @return Instance of View Manager
   * @since 1.0
   */
  private ViewManager getViewManager() {

    // Try to get the View Manager from the Servlet Context
    ViewManager vm =
      (ViewManager) getServletContext().getAttribute(FBSKeys.VIEWMANAGER);

    // If this method is called for the first time, this attribute is not set and hence
    // we need to instantiate a new instance.
    if (vm == null) {

      // Create a new instance and initialize it.
      vm = new ViewManager();

      vm.init(getServletContext());

      // Put this instance as attribute of Servlet Context
      getServletContext().setAttribute(FBSKeys.VIEWMANAGER, vm);
    }

    return vm;
  }

  /**
   * Method to set the Header for preventing caching of pages.
   *
   * @param response The response object of the Servlet.
   * @exception ServletException
   * @exception IOException
   * @since 1.0
   */
  public void setHeader(HttpServletResponse response)
          throws ServletException, IOException {

    // The following lines of code are added to prevent the caching of pages
    // which is the default behaviour in some browsers.
    // By setting the headers, the previous history is not maintained
    // so once the user logs out, the pages-visited previously cannot be navigated to
    response.setHeader("Cache-Control", "no-cache");  // HTTP 1.1
    response.setHeader("Pragma", "no-cache");         // HTTP 1.0
    response.setDateHeader("Expires", -1);  // Prevents caching at the proxy server
  }
}


⌨️ 快捷键说明

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