Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 7

Front Controller: Purpose and Structure

Recommended resources

Hello! Welcome to your seventh lesson on Java backend development.

In our last lesson, we explored the Model-View-Controller (MVC) design pattern. We saw how it separates an application's concerns into the Model (data and business logic), the View (presentation), and the Controller (request handling). We used a separate Servlet for each controller action, which is a great starting point but can become difficult to manage in larger applications.

Today, we'll build on that foundation by examining the Front Controller design pattern. This lesson addresses the learning outcome: Describe the purpose and structure of the Front Controller design pattern.

This pattern introduces a single, centralized point of entry for all requests, streamlining your application's architecture. It's a critical concept because it forms the backbone of modern web frameworks like Spring MVC. Understanding it is the final step in our foundational journey before we dive into the Spring framework itself.

The Problem with Many Controllers

Imagine an e-commerce application. You might have servlets for:

  • ViewProductServlet
  • AddToCartServlet
  • CheckoutServlet
  • LoginServlet
  • SearchServlet

As the application grows, so does the number of servlets. Each needs to be mapped in the web.xml deployment descriptor. Furthermore, common tasks like checking if a user is logged in, logging request details, or setting character encoding would need to be implemented in every servlet, leading to code duplication. While Servlet Filters (which we've covered) can help, the Front Controller pattern offers a more integrated architectural solution.


The Solution: The Front Controller Pattern

The Front Controller pattern solves this by channeling all incoming requests through a single handler object. This single servlet acts as a gatekeeper. It receives every request, performs common processing, and then delegates the request to other, more specialized components that handle the actual business logic.

Let's start by getting a formal definition of the pattern and its core components.

Front Controller Design Pattern in Java

The article 'Front Controller Design Pattern in Java' from dotnettutorials.net provides a clear introduction to the pattern and breaks down its key components. This will give us our foundational vocabulary.

Please read the first two main sections: 'What is Front Controller Design Pattern?' and 'Components of Front Controller Design Pattern'. Focus on understanding the roles of the Front Controller, Command Handlers (or Actions), and Views.

From the reading, you can see the main players are:

  • Front Controller: The single entry point for all requests. In a Java web app, this is typically a Servlet.
  • Command Handlers (or just Commands): These are objects responsible for the specific logic of a request. For example, you might have a LoginCommand or a ViewProductCommand. They encapsulate the business logic that would have otherwise been inside individual servlets.
  • Views: The same as in MVC—the presentation layer (e.g., JSP files) that renders the final output.

The following class diagram visually represents how these components can be structured.

UML Class Diagram of Front Controller Design Pattern
This diagram illustrates the relationships in a Front Controller implementation. The `FrontController` receives the request and uses a `Dispatcher` to delegate to a specific `Page` (which acts as both the Command and the View in this simple example).

How It Works: The Request-Handling Flow

Now that we know the components, let's trace the flow of a request from the client to the response.

  1. A client sends an HTTP request (e.g., /app/product?id=123).
  2. The Servlet Container, based on the URL mapping in web.xml, routes the request to our single Front Controller Servlet.
  3. The Front Controller performs common processing (e.g., security checks, logging).
  4. It then inspects the request to determine what action to take. It might look at a URL pattern or a request parameter (e.g., ?command=viewProduct).
  5. It delegates the request to the appropriate Command Handler (e.g., a ViewProductCommand object).
  6. The Command Handler executes the business logic. It interacts with the Model (your service and DAO layers) to fetch or update data.
  7. The Command Handler returns control to the Front Controller, often along with the data to be displayed and an identifier for the next View (e.g., the string "product-detail-page").
  8. The Front Controller uses a View Resolver (or a simple dispatcher) to forward the request and the data to the correct View (e.g., /WEB-INF/jsp/product-detail-page.jsp).
  9. The View renders the HTML response, which is sent back to the client.

This sequence diagram provides a great visual summary of this flow.

Front Controller Sequence Diagram
This sequence diagram shows the dynamic flow of a request. The client request goes to the FrontController (Servlet), which delegates to a helper (ApplicationController in this diagram) that invokes a specific Command and then dispatches to a View.

A More Concrete Java Implementation

The concept of a Command is central to this pattern. Let's look at a more practical, code-based example that shows how a FrontControllerServlet can dynamically execute commands.

A Guide to the Front Controller Pattern in Java

The article 'A Guide to the Front Controller Pattern in Java' on Baeldung.com provides an excellent, realistic implementation using a servlet. This example demonstrates how you can add new functionality without changing the Front Controller itself.

Please read section 3, focusing on subsections '3.3. FrontControllerServlet' and '3.4. FrontCommand'. You don't need to worry about the Maven setup or model details. Pay close attention to how the FrontControllerServlet uses Class.forName() to dynamically create a command object based on a request parameter, and how the abstract FrontCommand class provides a template for all commands.

This dynamic approach is powerful. The FrontControllerServlet doesn't need to know about SearchCommand or any other specific command at compile time. It simply loads and executes the class whose name is passed in the request. This makes the system highly extensible.

Test your understanding!

In the Baeldung example, a request to /?command=Search&title=... is handled by the SearchCommand class. If you wanted to add functionality to let an admin delete a book, how would you do it using this pattern?

  1. Would you modify the FrontControllerServlet?
  2. What new class(es) would you create?
  3. What would a sample URL look like to trigger this new functionality?
Show answer
  1. No, you would not need to modify the FrontControllerServlet. Its logic is generic and capable of handling any new command.
  2. You would create a new class, for example, DeleteBookCommand, that extends FrontCommand and implements the process() method to contain the book deletion logic. You would also create a corresponding view, like book-deleted.jsp.
  3. A sample URL might be /?command=DeleteBook&title=... or /?command=DeleteBook&id=.... The Front Controller would see command=DeleteBook, dynamically load DeleteBookCommand.class, and execute it.

Advantages and Disadvantages

Like any design pattern, the Front Controller has trade-offs. It's important to understand them.

Advantages:

  • Centralized Control: All requests go through one point, making it easy to manage cross-cutting concerns like security, logging, and internationalization.
  • Improved Reusability & Maintainability: Business logic is encapsulated in discrete Command objects, which are easier to test, reuse, and maintain than large servlets.
  • Clear Separation of Concerns: The roles of request dispatching (Front Controller), business logic (Commands), and presentation (Views) are clearly separated.

Disadvantages:

  • Single Point of Failure: If the Front Controller has a bug, the entire application can go down.
  • Potential Performance Overhead: The extra layer of indirection can add a small amount of latency to each request compared to a direct servlet-to-logic mapping, though this is rarely an issue in practice.
  • Increased Initial Complexity: Setting up the pattern requires more initial effort and classes than writing a single servlet for a simple task.

The Bridge to Spring MVC: DispatcherServlet

You've now done the hard work of understanding the theory behind modern Java web architecture. The great news is that you rarely have to implement this pattern from scratch. Frameworks like Spring MVC provide a powerful, flexible, and battle-tested implementation for you.

In Spring MVC, the Front Controller is called the DispatcherServlet. It does everything we've discussed and more, handling request mapping, view resolution, and data binding in a highly configurable way.

Let's watch a short video that ties these concepts together and shows how the Front Controller pattern is realized in Spring.

Spring MVC Architecture Workflow - Explained in Easy Way!

The video 'Spring MVC Architecture Workflow' gives a fantastic overview of how Spring's DispatcherServlet works as a Front Controller. This will serve as a perfect preview for our next topic.

Watch from the beginning to 03:29. Notice how the video's description of the flow mirrors what we've just learned: the request goes to the Front Controller (DispatcherServlet), which uses a HandlerMapping to find the right controller (our 'Command'), which then returns a model and a view name.


Conclusion

In this lesson, we've elevated our application architecture from a simple MVC to a more robust and scalable structure using the Front Controller pattern.

Key Takeaways:

  • The Front Controller pattern centralizes all request handling through a single entry point, usually a servlet.
  • It decouples request handling from business logic by delegating tasks to specific Command Handlers.
  • This structure promotes separation of concerns, making the application more modular, maintainable, and extensible.
  • Spring MVC's DispatcherServlet is a powerful, real-world implementation of the Front Controller pattern.

What's Next?

You have now completed the foundational module on Java Web and MVC concepts! You understand the request/response cycle, the role of servlets and filters, and the key architectural patterns (MVC and Front Controller) that underpin modern frameworks.

In our next lesson, we will officially begin our journey with the Spring Framework. We will start by examining how Spring's DispatcherServlet implements the Front Controller pattern, taking the concepts we learned today and seeing them in the context of a real Spring application. This will be the final piece of the puzzle connecting the "why" to the "how" of Spring web development.