Files
java-design-patterns/front-controller/README.md
T
Ilkka Seppälä 6cd2d0353a docs: Content SEO updates (#2990)
* update yaml frontmatter format

* update abstract document

* update abstract factory

* use the new pattern template

* acyclic visitor seo

* adapter seo

* ambassador seo

* acl seo

* aaa seo

* async method invocation seo

* balking seo

* bridge seo

* builder seo

* business delegate and bytecode seo

* caching seo

* callback seo

* chain seo

* update headings

* circuit breaker seo

* client session + collecting parameter seo

* collection pipeline seo

* combinator SEO

* command seo

* cqrs seo

* commander seo

* component seo

* composite seo

* composite entity seo

* composite view seo

* context object seo

* converter seo

* crtp seo

* currying seo

* dao seo

* data bus seo

* data locality seo

* data mapper seo

* dto seo

* decorator seo

* delegation seo

* di seo

* dirty flag seo

* domain model seo

* double buffer seo

* double checked locking seo

* double dispatch seo

* dynamic proxy seo

* event aggregator seo

* event-based asynchronous seo

* eda seo

* event queue seo

* event sourcing seo

* execute around seo

* extension objects seo

* facade seo

* factory seo

* factory kit seo

* factory method seo

* fanout/fanin seo

* feature toggle seo

* filterer seo

* fluent interface seo

* flux seo

* flyweight seo

* front controller seo

* function composition seo

* game loop seo

* gateway seo

* guarded suspension seo

* half-sync/half-async seo

* health check seo

* hexagonal seo

* identity map seo

* intercepting filter seo

* interpreter seo

* iterator seo

* layers seo

* lazy loading seo

* leader election seo

* leader/followers seo

* lockable object seo

* rename and add seo for marker interface

* master-worker seo

* mediator seo

* memento seo

* metadata mapping seo

* microservice aggregator seo

* api gw seo

* microservices log aggregration seo

* mvc seo

* mvi seo

* mvp seo

* mvvm seo

* monad seo

* monitor seo

* monostate seo

* multiton seo

* mute idiom seo

* naked objects & notification seo

* null object seo

* object mother seo

* object pool seo

* observer seo

* optimistic locking seo

* page controller seo

* page object seo

* parameter object seo

* partial response seo

* pipeline seo

* poison pill seo

* presentation model seo

* private class data seo

* producer-consumer seo

* promise seo

* property seo

* prototype seo

* proxy seo

* queue-based load leveling seo

* reactor seo

* registry seo

* repository seo

* RAII seo

* retry seo

* role object seo

* saga seo

* separated interface seo

* serialized entity seo

* serialized lob seo

* servant seo

* server session seo

* service layer seo

* service locator seo

* service to worker seo

* sharding seo

* single table inheritance seo

* singleton seo

* spatial partition seo

* special case seo

* specification seo

* state seo

* step builder seo

* strangler seo

* strategy seo

* subclass sandbox seo

* table module seo

* template method seo

* throttling seo

* tolerant reader seo

* trampoline seo

* transaction script seo

* twin seo

* type object seo

* unit of work seo

* update method seo

* value object seo

* version number seo

* virtual proxy seo

* visitor seo

* seo enhancements

* seo improvements

* SEO enhancements

* SEO improvements

* SEO additions

* SEO improvements

* more SEO improvements

* rename hexagonal + SEO improvements

* SEO improvements

* more SEO stuff

* SEO improvements

* SEO optimizations

* SEO enhancements

* enchance SEO

* improve SEO

* SEO improvements

* update headers
2024-06-08 19:54:44 +03:00

144 lines
6.7 KiB
Markdown

---
title: "Front Controller Pattern in Java: Centralizing Web Request Handling"
shortTitle: Front Controller
description: "Explore the Front Controller design pattern in Java for centralized request handling. Learn how to improve web application efficiency and consistency with this architectural pattern."
category: Architectural
language: en
tag:
- Architecture
- Decoupling
- Enterprise patterns
- Layered architecture
- Web development
---
## Also known as
* Centralized Request Handling
## Intent of Front Controller Design Pattern
The Front Controller design pattern aims to provide a centralized entry point for handling all incoming web requests. This pattern ensures consistent and efficient request routing and management across a Java web application.
## Detailed Explanation of Front Controller Pattern with Real-World Examples
Real-world example
> In a real-world scenario, a front desk in a hotel serves as the centralized request handling point, similar to how the Front Controller design pattern functions in web application architecture. This desk acts as the "front controller" of the hotel, responsible for receiving all inquiries, from room service orders to maintenance requests. The receptionist assesses each request and routes it to the appropriate department—housekeeping, the kitchen, or maintenance. This system centralizes request handling, ensuring that guest needs are addressed efficiently and consistently, similar to how a Front Controller in a software application manages all incoming requests and delegates them to specific handlers.
In plain words
> The Front Controller design pattern centralizes incoming web requests into a single handling point, allowing consistent processing and delegation across an application.
Wikipedia says
> The front controller software design pattern is listed in several pattern catalogs and is related to the design of web applications. It is "a controller that handles all requests for a website", which is a useful structure for web application developers to achieve flexibility and reuse without code redundancy.
## Programmatic Example of Front Controller Pattern in Java
The Front Controller design pattern is a pattern that provides a centralized entry point for handling all requests in a web application. It ensures that request handling is managed consistently and efficiently across an application.
In the provided code, we can see an example of the Front Controller pattern in the `App`, `FrontController` and `Dispatcher` classes.
The `App` class is the entry point of the application. It creates an instance of `FrontController` and uses it to handle various requests.
```java
public class App {
public static void main(String[] args) {
var controller = new FrontController();
controller.handleRequest("Archer");
controller.handleRequest("Catapult");
controller.handleRequest("foobar");
}
}
```
The `FrontController` class is the front controller in this example. It handles all requests and delegates them to the `Dispatcher`.
```java
public class FrontController {
private final Dispatcher dispatcher;
public FrontController() {
this.dispatcher = new Dispatcher();
}
public void handleRequest(String request) {
dispatcher.dispatch(request);
}
}
```
The `Dispatcher` class is responsible for handling the dispatching of requests to the appropriate command. It retrieves the corresponding command based on the request and invokes the command's process method to handle the business logic.
```java
public class Dispatcher {
public void dispatch(String request) {
var command = getCommand(request);
command.process();
}
Command getCommand(String request) {
var commandClass = getCommandClass(request);
try {
return (Command) commandClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new ApplicationException(e);
}
}
static Class<?> getCommandClass(String request) {
try {
return Class.forName("com.iluwatar.front.controller." + request + "Command");
} catch (ClassNotFoundException e) {
return UnknownCommand.class;
}
}
}
```
In this example, when a request is received, the `FrontController` delegates the request to the `Dispatcher`, which creates a command object based on the request and calls its `process` method. The command object is responsible for handling the request and rendering the appropriate view.
This is a basic example of the Front Controller pattern, where all requests are handled by a single controller and dispatcher, ensuring consistent and efficient request handling.
## Detailed Explanation of Front Controller Pattern with Real-World Examples
![Front Controller](./etc/front-controller.png "Front Controller")
## When to Use the Front Controller Pattern in Java
* The Front Controller design pattern is particularly useful for Java web applications that require a centralized mechanism for request handling.
* Systems that need a common processing point for all requests to perform tasks such as authentication, logging, and routing.
## Real-World Applications of Front Controller Pattern in Java
* [Apache Struts](https://struts.apache.org/)
* Java web frameworks like Spring MVC and JavaServer Faces (JSF) implement the Front Controller pattern through their central dispatcher servlet, which manages web requests and delegates responsibilities.
## Benefits and Trade-offs of Front Controller Pattern
Benefits:
* The main benefit of the Front Controller design pattern is the centralization of request handling, which simplifies maintenance and ensures consistent behavior across the application.
* Eases the integration of services like security and user session management.
* Facilitates common behavior like routing, logging, and authentication across requests.
Trade-offs:
* Can become a bottleneck if not properly managed.
* Increases complexity in the dispatcher controller, requiring careful design to avoid tight coupling.
## Related Java Design Patterns
* [Page Controller](https://java-design-patterns.com/patterns/page-controller/): Front Controller can delegate requests to Page Controllers, which handle specific page requests. This division supports the Single Responsibility Principle.
* [Model-View-Controller (MVC)](https://java-design-patterns.com/patterns/model-view-controller/): Front Controller acts as the controller, managing the flow between model and view.
* [Command](https://java-design-patterns.com/patterns/command/): Can be used to encapsulate a request as an object, which the Front Controller can manipulate and delegate.
## References and Credits
* [J2EE Design Patterns](https://amzn.to/4dpzgmx)
* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)