Advertisment

Front Controller

author-image
CIOL Bureau
Updated On
New Update

Avijeet Dash and Satyabrata

Dash

Advertisment

This Front Controller in a generic way delegates the functionalities like

validation of user data, calling of business services to a command or a helper

component.

The presentation-tier request handling mechanism must control and coordinate

processing of each user across multiple requests. Such control mechanisms may be

managed in either a centralized or decentralized manner.

If managed in a decentralized manner, it will lead to code duplication for

the common set of functionalities like content retrieval, view management, and

navigation.

Advertisment

Typically we write specific servlets for specific request handling. These

servlets do validation of the data entered, and error handling if data entered

is in valid, and if everything is fine they create some sort of data object

containing the data entered by the user and invoke the business service method

to do the necessary action and then forward the request to specific view to

display the results to the user.

Front Controller suggests a different approach, where we have only one

servlet centralizing the handling of all requests. We can have multiple Front

Controllers in a system, each mapping to a set of distinct services.

This Front Controller in a generic way delegates the functionalities like

validation of user data, calling of business services to a command or a helper

component. It delegates the functionality of choosing the next view to a

Dispatch component either contained in the Front Controller as a method or used

as a different component.

Advertisment

The controller manages the handling of the request including invoking

security services such as authentication and authorization, delegation business

processing, managing appropriate view, handling errors and managing the

selection of the content creation strategy.

Sequence diagram of Front

Controller

Advertisment

Controller

The FrontController is the initial contact point for handling all requests in

the system. The FrontController typically interacts with the Dispatcher. The

Front Controller may delegate to a Helper to complete authentication and

authorization of a user, or to initiate content retrieval.

Advertisment

Dispatcher

Advertisment

A Dispatcher is responsible for view management and navigation, managing the

choice of the next View to present to the user and providing the mechanism for

vectoring control to this resource.

A Dispatcher can be encapsulated within a Controller or can be a separate

component working in coordination. The Dispatcher can provide static dispatching

to the View or may provide a more sophisticated dynamic dispatching mechanism.

The Dispatcher will use the RequestDispatcher object (supported in the

Servlet specification) and will encapsulate some additional processing.

Advertisment

Helper

A Helper is responsible for helping a View or Controller complete its

processing. Thus, Helpers have numerous responsibilities, including gathering

data required by the View and adapting this data model

for use by the View. Helpers can service requests for data from the View by

simply providing access to the raw data or by formatting the data as web

content.

A View may work with any number of Helpers, which are typically implemented

as JavaBeansTM (JSPTM 1.0) and Custom Tags (JSP 1.1+).

Additionally, a Helper may represent a Command object, a Delegate (see Business

Delegate pattern), or an XSL Transformer, which is used in combination with a

stylesheet to adapt and convert the model into the appropriate form.

View

A View represents and displays information to the client. The information

that is used in a display is retrieved from a model. Helpers support Views by

encapsulating and adapting a model for use in a display

Example Servlet Front Strategy Sample Code

public class EmployeeController extends HttpServlet {
  // Initializes the servlet.
  public void init(ServletConfig config) throws
    ServletException {
    super.init(config);
  }

  // Destroys the servlet.
  public void destroy() {
  }

  /** Processes requests for both HTTP
   * GET and POST methods.
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest
    request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    String page;

    /**ApplicationResources provides a simple API
     * for retrieving constants and other
     * preconfigured values**/
    ApplicationResources resource =
      ApplicationResources.getInstance();
    try {

      // Use a helper object to gather parameter
      // specific information.
      RequestHelper helper = new
         RequestHelper(request);

      Command cmdHelper= helper.getCommand();

      // Command helper perform custom operation
      page = cmdHelper.execute(request, response);

    }
    catch (Exception e) {
      LogManager.logMessage(
        "EmployeeController:exception : " +
        e.getMessage());
      request.setAttribute(resource.getMessageAttr(),
        "Exception occurred : " + e.getMessage());
      page = resource.getErrorPage(e);
    }
    // dispatch control to view
    dispatch(request, response, page);
  }

  /** Handles the HTTP GET method.
   * @param request servlet request
   * @param response servlet response
   */
  protected void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, java.io.IOException {
      processRequest(request, response);
  }

  /** Handles the HTTP POST method.
   * @param request servlet request
   * @param response servlet response
   */
  protected void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
  }

  /** Returns a short description of the servlet */
  public String getServletInfo() {
    return "Front Controller Pattern" +
      " Servlet Front Strategy Example";
  }

  protected void dispatch(HttpServletRequest request,
    HttpServletResponse response,
    String page)
  throws  javax.servlet.ServletException,
    java.io.IOException {
    RequestDispatcher dispatcher =
      getServletContext().getRequestDispatcher(page);
    dispatcher.forward(request, response);
  }
}

Command and Controller Strategy - Struts

Based on the Command pattern , the Command and Controller

Strategy
suggests providing a generic interface to the helper components to

which the controller may delegate responsibility, minimizing the coupling among

these components (See the ViewHelper pattern for more information on

Helper components). Adding to or changing the work that needs to be completed by

these helpers does not require any changes to the interface between the

controller and the helpers, but rather to the type and/or content of the

commands. This provides a flexible and easily extensible mechanism for

developers to add request handling behaviors.

Finally, because the command processing is not coupled to the command

invocation, the command processing mechanism may be reused with various types of

clients, not just web browsers. This strategy also facilitates the creation of

composite commands (see Composite Pattern ).

Struts is a

good example of Command and Controller strategy

 Struts includes the following primary areas of functionality:

    • A controller servlet that dispatches requests to appropriate Action

      classes provided by the application developer.
    • JSP custom tag libraries, and associated support in the controller

      servlet, that assists developers in creating interactive form-based

      applications.
    • Utility classes to support XML parsing, automatic population of

      JavaBeans properties based on the Java reflection APIs, and

      internationalization of prompts and messages.

Front Controller centralizes control providing a central place to handle

system services and business logic across multiple requests. The Front

Controller pattern in conjunction with the View Helper pattern, describes

factoring business logic out of the view and providing a central point of

control and dispatch. Flow logic is factored forward into the controller and

data handling code moves back into helpers
.

 

Reference:

Core J2EE Patterns, Deepak Alur, John Crupi, Dan Malks

http://developer.java.sun.com/developer/technicalArticles/J2EE/patterns/

tech-news