Java Front Controller [duplicate]

To start, create a Servlet which listens on a certain url-pattern, e.g. /pages/*. Implement the service() method to lookup the action associated with the request method (GET, POST, etc) and pathinfo (the URL part after the servlet’s url-pattern).

Basic example:

protected void service(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException {
  View view = new View(request, response);
  Action action = ActionFactory.getAction(request);
  action.execute(view);
  view.navigate();
}

The Action interface should represent an unit of work. You can implement it to do the necessary business logic:

public interface Action {
  void execute(View view);
}

The ActionFactory should maintain the classes implementing Action in sort of Map<String, Action> where the String key represents less or more a combination of the request method and pathinfo. You could then get an Action as follows:

public static Action getAction(HttpServletRequest request) {
  return actions.get(request.getMethod() + request.getPathInfo());
}

The View should represent the request scoped context which the Action can work with. In the navigate() you could forward the request to a JSP for display:

public void navigate() {
  String path = "/WEB-INF" + request.getPathInfo() + ".jsp";
  request.getRequestDispatcher(path).forward(request, response);
}

That should get you started (note that I left all obvious checks such as null pointers away to make the examples less cluttered, that’s up to you now).

There is however more to take account with in the whole story, such as validation, conversion, event handling, input value mappings, localization, dependency injection, etcetera. That’s all with all quite a work. The more decent MVC frameworks takes most of this all into account, such as Sun JSF, Apache Struts, Spring MVC, Stripes, etcetera. If you have never done any of them, then I strongly recommend to do so before homegrowing one, otherwise you would end up with a waste of time.

Leave a Comment