Front Controller pattern (Mediator pattern)

First, the Controller part should implement the Front Controller pattern (which is a specialized kind of Mediator pattern). It should consist of only a single servlet which provides a centralized entry point of all requests. It should create the Model based on information available by the request, such as the pathinfo or servletpath, the method and/or specific parameters. The Business Model is called Action in the below HttpServlet example.

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try {

Action action = ActionFactory.getAction(request);

String view = action.execute(request, response);

if (view.equals(request.getPathInfo().substring(1)) {

request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);

} else {

response.sendRedirect(view); // We'd like to fire redirect in case of a view change as result of the action (PRG pattern).

}

} catch (Exception e) {

throw new ServletException("Executing action failed.", e);

}

}

Executing the action should return some identifier to locate the view. Simplest would be to use it as filename of the JSP. Map this servlet on a specific url-pattern in web.xml, e.g. /pages/, .do or even just *.html.

In case of prefix-patterns as for example /pages/* you could then invoke URL's likehttp://example.com/pages/register, http://example.com/pages/login, etc and provide /WEB-INF/register.jsp, /WEB-INF/login.jsp with the appropriate GET and POST actions. The partsregister, login, etc are then available by request.getPathInfo() as in above example.

When you're using suffix-patterns like .do, .html, etc, then you could then invoke URL's likehttp://example.com/register.do, http://example.com/login.do, etc and you should change the code examples in this answer (also the ActionFactory) to extract the register and login parts by request.getServletPath() instead.

results matching ""

    No results matching ""