Refactor large Controllers
HttpServlet are sometimes informally called Controller classes (or Action classes).
They form the entry point of client HTTP requests into a web app.
A common problem with Controllers is that they become too large.
Since the flow of control starts out in the Controller, there's a strong tendency to keep adding more and more code to the same place.
But that's usually a mistake.
You should not really think of the Controller as being in control.
Rather, you should think of the Service as being in control.
(From this perspective, the term Controller is a bit of a misnomer.)
Here's a summary of the distinction between Controller and Service:
As such, Controller classes should usually be fairly compact.
If your Controller methods become large, or have service-logic in them, then you should consider moving that code into a Service class of some sort.
- the Service has the most important things: access to the database, and all associated data-logic and data-operations.
(In this context, the word Service is meant to include Data Access Objects.)
- the Controller has the less important things: access to the incoming HTTP request, and the outgoing HTTP response.
- the Controller's job is to be an input-output mechanism for the Service: it translates incoming HTTP requests into usable data, and it forwards outgoing data to a JSP for a final HTTP response.
- the Service is completely ignorant of HTTP.
- for testing, the Service only needs access to the database; it doesn't need HTTP.
(The distinction between Controller and Service can be more than just a desire for clear design.
When using the Spring framework, there are actually some important functional differences between Controller and Service classes.)
See Also :