Front Controller Design Pattern in Java

In this tutorial, we will explore the Front Controller Design Pattern in Java. The Front Controller pattern provides a centralized request-handling mechanism so that all requests are handled by a single handler. This pattern is often used in web applications to manage requests and direct them to the right controllers.

What You’ll Learn:

  • Understanding the Front Controller Pattern.
  • Setting up a Maven project.
  • Implementing the Front Controller pattern in Java.
  • Demonstrating the pattern with a simple Servlet-like example.
  • Output and explanation.

Introduction to the Front Controller Pattern

The Front Controller Pattern involves a central controller that handles all client requests and then forwards them to appropriate handlers (controllers). This pattern simplifies request handling by having a single point of entry, which can also be used to apply cross-cutting concerns like logging, authentication, or request preprocessing.

Key Components of the Pattern:

  1. Front Controller: A single handler for incoming requests.
  2. Dispatcher: Forwards the request to the appropriate handler.
  3. Handlers/Controllers: Processes the request and generates a response.

Advantages:

  • Centralized control for request handling.
  • Easy to implement pre-processing (authentication, logging) and post-processing (response formatting).
  • Simplifies adding new request types.

Step 1: Setting Up the Project

1.1 Create a Maven Project

  1. Open your IDE (e.g., IntelliJ IDEA, Eclipse).
  2. Create a new Maven project.

1.2 Add Dependencies

In this example, no specific third-party dependencies are required, but we’ll use the standard Java 21 features. Update the pom.xml to configure the Java compiler plugin:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>front-controller-pattern</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
                <configuration>
                    <source>21</source>
                    <target>21</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Explanation:

  • Maven Compiler Plugin is configured to use Java 21 for building and running the project.

Step 2: Implementing the Front Controller Pattern

We will create the necessary components step-by-step: Front Controller, Dispatcher, and Handlers.

2.1 Create Dispatcher Class

The Dispatcher is responsible for forwarding requests to the appropriate handler.

In the com.example.frontcontroller package, create a Dispatcher class:

package com.example.frontcontroller;

public class Dispatcher {
    private final HomeController homeController;
    private final ProductController productController;

    public Dispatcher() {
        this.homeController = new HomeController();
        this.productController = new ProductController();
    }

    public void dispatch(String request) {
        if (request.equalsIgnoreCase("HOME")) {
            homeController.showHomePage();
        } else if (request.equalsIgnoreCase("PRODUCT")) {
            productController.showProductPage();
        } else {
            System.out.println("404 Page Not Found");
        }
    }
}

Explanation:

  • The Dispatcher contains logic to determine which controller (handler) should handle the request.
  • Depending on the request string ("HOME" or "PRODUCT"), the request is forwarded to the corresponding controller.

2.2 Create Controllers (Handlers)

The Handlers or Controllers are responsible for processing the request and generating the appropriate response.

2.2.1 HomeController Class

Create a HomeController class:

package com.example.frontcontroller;

public class HomeController {
    public void showHomePage() {
        System.out.println("Displaying Home Page");
    }
}

2.2.2 ProductController Class

Create a ProductController class:

package com.example.frontcontroller;

public class ProductController {
    public void showProductPage() {
        System.out.println("Displaying Product Page");
    }
}

Explanation:

  • Each controller handles a specific type of request. The HomeController handles the request for the homepage, while the ProductController handles the request for the product page.

2.3 Create the Front Controller

The Front Controller is responsible for receiving and delegating all requests to the dispatcher.

Create the FrontController class:

package com.example.frontcontroller;

public class FrontController {
    private final Dispatcher dispatcher;

    public FrontController() {
        this.dispatcher = new Dispatcher();
    }

    public void handleRequest(String request) {
        System.out.println("Front Controller: Processing request - " + request);
        dispatcher.dispatch(request);
    }
}

Explanation:

  • The FrontController receives the incoming request and logs it. It then passes the request to the Dispatcher, which directs it to the appropriate handler.

Step 3: Demonstrating the Front Controller Pattern

Now, let’s demonstrate the Front Controller Pattern in action by creating a MainApp class that simulates incoming requests.

3.1 Create MainApp Class

In the com.example.frontcontroller package, create the MainApp class:

package com.example.frontcontroller;

public class MainApp {
    public static void main(String[] args) {
        FrontController frontController = new FrontController();

        System.out.println("----- Simulating Requests -----");

        // Simulate requests
        frontController.handleRequest("HOME");
        frontController.handleRequest("PRODUCT");
        frontController.handleRequest("CONTACT");  // Invalid request
    }
}

Explanation:

  • MainApp simulates requests being handled by the FrontController.
    • "HOME" and "PRODUCT" requests are valid and are handled by their respective controllers.
    • "CONTACT" is an invalid request and will result in a 404 Page Not Found response.

Step 4: Running the Application

To run the application, simply execute the MainApp class. If you're using an IDE, click the Run button.

Expected Output

----- Simulating Requests -----
Front Controller: Processing request - HOME
Displaying Home Page
Front Controller: Processing request - PRODUCT
Displaying Product Page
Front Controller: Processing request - CONTACT
404 Page Not Found

Explanation:

  • When a "HOME" request is processed, the HomeController displays the Home Page.
  • When a "PRODUCT" request is processed, the ProductController displays the Product Page.
  • When an invalid request ("CONTACT") is received, a 404 Page Not Found error is displayed.

Conclusion

In this tutorial, we explored the Front Controller Design Pattern in Java. We built a simple application to demonstrate how this pattern works by centralizing request handling through a Front Controller. We created different components such as the Dispatcher, HomeController, and ProductController to handle specific requests and demonstrate the flexibility and simplicity of this design pattern.

This example provides a clean and maintainable architecture for handling requests in a centralized way, making it easy to add additional functionality like logging, authentication, or request validation.

Comments

  1. Thanks for sharing this valuable information.and I gathered some information from this blog...Apply online for Indian Postal Recruitment for Postman/Mail Guard, Postal Assistant, Sorting Assistant, MTS-Multi Tasking Staff, etc. Indian Postal Recruitment 2020 provides challenging Platform for Graduates, Freshers and experienced candidates...

    ReplyDelete

Post a Comment

Leave Comment