Front controller

Last updated

The front controller software design pattern is listed in several pattern catalogs and related to the design of web applications. It is "a controller that handles all requests for a website", [1] which is a useful structure for web application developers to achieve flexibility and reuse without code redundancy.

Contents

Instruction

A typical front controller structure. Front Controller.svg
A typical front controller structure.

Front controllers are often used in web applications to implement workflows. While not strictly required, it is much easier to control navigation across a set of related pages (for instance, multiple pages used in an online purchase) from a front controller than it is to make the individual pages responsible for navigation.

The front controller may be implemented as a Java object, or as a script in a script language like PHP, Raku, Python or Ruby that is called on every request of a web session. This script, for example an index.php, would handle all tasks that are common to the application or the framework, such as session handling, caching, and input filtering. Based on the specific request, it would then instantiate further objects and call methods to handle the particular task(s) required.

The alternative to a front controller would be individual scripts like login.php and order.php that would each then satisfy the type of request. Each script would have to duplicate code or objects that are common to all tasks. However, each script might also have more flexibility to implement the particular task required.

Examples

Several web-tier application frameworks implement the front controller pattern, among them:

Implementation

To better understand front controller pattern, there is an example to implement front controller in Java. [3] It can be defined in 3 components:

  1. XML Mapping: files that map requests to the class that will handle the request processing.
  2. Request Processor: used for dealing with the request processing (and modifying or retrieving the appropriate model).
  3. Flow Manager: first get the request and the output of the processing, then determine what will show on the next page.

Participants and responsibilities

ControllerDispatcherHelperView
The controller is an entrance for users to handle requests in the system. It realizes authentication by playing the role of delegating helper or initiate contact retrieval.Dispatchers can be used for navigation and managing the view output. Users will receive next view that is determined by the dispatcher. Dispatchers are also flexible: they can be encapsulated within the controller directly or separated to another component. The dispatcher provides a static view along with the dynamic mechanism.

It also uses the RequestDispatcher object (supported in the servlet specification) and encapsulates some additional processing.

A helper helps view or controller to process. Thus helper can achieve various goals.

At view side, the helper collects data and sometimes stores data as an intermediate station. Before view's process, helpers serve to adapt the data model for it. Helpers do certain pre-processes such as formatting the data to web content or providing direct access to the raw data. Multiple helpers can collaborate with one view for most conditions. They are implemented as JavaBeans components in JSP 1.0+ and custom tags in JSP 1.1+. Additionally, a helper also works as a transformer that is used to adapt and convert the model into the suitable format.

With the collaboration of helpers, view displays information to the client. It processes data from a model. The view will display if the processing succeeds and vice versa.

Demo implementation in Java

Here is part of a demo code to implement front controller. [4]

privatevoiddoProcess(HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException,ServletException{...try{getRequestProcessor().processRequest(request);getScreenFlowManager().forwardToNextScreen(request,response);}catch(Throwableex){StringclassName=ex.getClass().getName();nextScreen=getScreenFlowManager().getExceptionScreen(ex);// Put the exception in the requestrequest.setAttribute("javax.servlet.jsp.jspException",ex);if(nextScreen==null){// Send to general error screenex.printStackTrace();thrownewServletException("MainServlet: unknown exception: "+className);}}

Benefits and liabilities

There are three benefits for using front controller pattern. [5]

In terms of liability, front controllers that determine the following activities by searching the database or XML documents, performance might be decreased. And implementation of front controller to existed systems always involving replacing the current ones, which makes it harder for beginners to start with.

Relationship with MVC pattern

  1. In order to improve system reliability and maintainability, duplicated codes should be avoided and centralized when they are of the same common logic through the whole system.
  2. The data for the application is better to be handled in one location, thus there will be no need to duplicate database retrieval code.
  3. Different roles in the MVC pattern should be separated to increase testability, which is also true for controller part in the MVC pattern.

Comparison

Page controller is an alternative to front controller in MVC model.

Page ControllerFront Controller
Base classBase class is needed and will grow simultaneously with the development of the application.The centralization of solving all requests is easier to modify than base class method.
SecurityLow security because various objects react differently without consistency.High. The controller is implemented in coordinated fashion, making the application safer.
Logical PageSingle object on each logical page.Only one controller handles all requests.
ComplexityLowHigh

See also

Related Research Articles

Jakarta Servlet Jakarta EE programming language class

A Jakarta Servlet is a Java software component that extends the capabilities of a server. Although servlets can respond to many types of requests, they most commonly implement web containers for hosting web applications on web servers and thus qualify as a server-side servlet web API. Such web servlets are the Java counterpart to other dynamic web content technologies such as PHP and ASP.NET.

Cocoa is Apple's native object-oriented application programming interface (API) for its desktop operating system macOS.

Model–view–controller Software design pattern

Model–view–controller is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.

JSP model 2 architecture

JSP Model 2 is a complex design pattern used in the design of Java Web applications which separates the display of content from the logic used to obtain and manipulate the content. Since Model 2 drives a separation between logic and display, it is usually associated with the model–view–controller (MVC) paradigm. While the exact form of the MVC "Model" was never specified by the Model 2 design, a number of publications recommend a formalized layer to contain MVC Model code. The Java BluePrints, for example, originally recommended using EJBs to encapsulate the MVC Model.

A web framework (WF) or web application framework (WAF) is a software framework that is designed to support the development of web applications including web services, web resources, and web APIs. Web frameworks provide a standard way to build and deploy web applications on the World Wide Web. Web frameworks aim to automate the overhead associated with common activities performed in web development. For example, many web frameworks provide libraries for database access, templating frameworks, and session management, and they often promote code reuse. Although they often target development of dynamic web sites, they are also applicable to static websites.

Laminas Project is an open source, object-oriented web application framework implemented in PHP 7 and licensed under the New BSD License. The framework is basically a collection of professional PHP-based packages. The framework uses various packages by the use of Composer as part of its package dependency managers; some of them are PHPUnit for testing all packages, Travis CI for continuous Integration Services. Laminas provides to users a support of the model–view–controller (MVC) in combination with Front Controller solution. MVC implementation in Laminas has five main areas. The router and dispatcher functions to decide which controller to run based on data from URL, and controller functions in combination with the model and view to develop and create the final web page.

The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Although the framework does not impose any specific programming model, it has become popular in the Java community as an addition to the Enterprise JavaBeans (EJB) model. The Spring Framework is open source.

Grails is an open source web application framework that uses the Apache Groovy programming language. It is intended to be a high-productivity framework by following the "coding by convention" paradigm, providing a stand-alone development environment and hiding much of the configuration detail from the developer.

PureMVC

PureMVC is a framework for creating applications based upon the well-established model–view–controller (MVC) design pattern. The free, open source framework was originally implemented in the ActionScript 3 language for use with Adobe Flex, Flash and AIR, and it has since been ported to nearly all the major web development platforms.

Model–view–presenter

Model–view–presenter (MVP) is a derivation of the model–view–controller (MVC) architectural pattern, and is used mostly for building user interfaces.

Java view technologies and frameworks are web-based software libraries that provide the user interface, or "view-layer", of Java web applications. Such application frameworks are used for defining web pages and handling the HTTP requests (clicks) generated by those web pages. As a sub-category of web frameworks, view-layer frameworks often overlap to varying degrees with web frameworks that provide other functionality for Java web applications.

ZK is an open-source Ajax Web application framework, written in Java, that enables creation of graphical user interfaces for Web applications with little required programming knowledge.

Model–view–viewmodel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface – be it via a markup language or GUI code – from the development of the business logic or back-end logic so that the view is not dependent on any specific model platform. The viewmodel of MVVM is a value converter, meaning the viewmodel is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented. In this respect, the viewmodel is more model than view, and handles most if not all of the view's display logic. The view model may implement a mediator pattern, organizing access to the back-end logic around the set of use cases supported by the view.

Jspx-bay

jspx-bay, commonly referred to as jspx, is a free open source pure Java web RAD framework. Jspx should not be confused with other technologies using the same name like Oracle Application Framework and XML JSP.

Mojito is an environment agnostic, Model-View-Controller (MVC) web application framework. It was designed by Ric Allinson.

Ember.js

Ember.js is an open-source JavaScript web framework, utilizing a component-service pattern. It allows developers to create scalable single-page web applications by incorporating common idioms, best practices, and patterns from other single-page-app ecosystem patterns into the framework.

JWt is an open-source widget-centric web application framework for the Java programming language developed by Emweb. It has an API that uses established GUI application development patterns. The programming model is component-based and event-driven, similar to Swing.

Laravel Open source web application framework, written in PHP

Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern and based on Symfony. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar.

Intercepting Filter is a JavaEE pattern which creates pluggable filters to process common services in a standard manner without requiring changes to core request processing code. The filters intercept incoming requests and outgoing responses, allowing preprocessing and post-processing, and these filters can be added or removed unobtrusively without changing existing code. This pattern applies reusable processing transparently before and after the actual request execution by the front and page controllers.

References

  1. Fowler, Martin. "Front Controller" . Retrieved September 26, 2017.
  2. "Web MVC framework". Spring Framework Reference Documentation. Pivotal Software . Retrieved September 26, 2017.
  3. "Front Controller Pattern".
  4. "Demo code in Java". Archived from the original on 2012-04-19.CS1 maint: bot: original URL status unknown (link)
  5. "Benefits for using front controller".

Notes