Front Controller Pattern
One handler receives every web request, runs the shared work once, and dispatches to the right command. Know how it differs from Page Controller, why filter order matters, and how Spring, Express and Django all build on it.
Overview
The Front Controller is one object that receives every request to a web application. It does the work that every request needs (checking who the caller is, logging, picking a language, checking a CSRF token) and then hands the request to a smaller piece of code that knows how to serve that one URL. Martin Fowler catalogs it in Patterns of Enterprise Application Architecture (2002) and describes it as a controller that handles all requests for a web site; in his version the shared handler passes request-specific work to command objects.
The problem it fixes is duplication at the edge. If every page has its own entry point, every page also has its own copy of the sign-in check and the logging. Sooner or later one copy is missing or out of date, and that page is the one with the security hole.
Interviewers use the pattern to check three things: whether you can contrast it with Page Controller, whether you know where cross-cutting work goes and why its order matters, and whether you recognize the pattern inside the frameworks you already use.
The shape
Picture one door into a building with many rooms. Every request comes through the same door and the same checks, and only the last step, the room, differs per URL.
The picture has four parts, and each has one job.
- Front controller: the one entry point, which owns the request algorithm. Spring's DispatcherServlet and an Express app are examples.
- Filter chain: the shared work before and after the handler, in a fixed order, such as session, authentication and logging middleware.
- Router (dispatcher): maps the method and path to one handler or command, as a route table or Django's urlpatterns does.
- Handler (command): the work for one action and nothing shared, such as get_order(request).
Interview questions
- What is the Front Controller pattern, and how is it different from Page Controller?
- Where do cross-cutting concerns go, and why does the order of filters matter?
- How does Spring MVC implement the Front Controller?
- How do you stop a front controller from becoming a god object?
- How should a front controller handle unknown routes and errors?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio