Issue
When building a java web app, sometimes we use Form classes for our model classes to "...save passing the ServletRequest to other components, such as validators. ServletRequest is a servlet-specific type and should not be exposed to other layers of the applications." Form classes are the same classes as the model classes, but not serializable.
The quote is from Servlets & JSP and Spring MVC tutorial. I am trying to understand the second statement, i.e. that the ServletRequest object is exposed. Is this a best practice for security reasons? If someone could explain, it would be great. Obviously, implementing this requires a lot of code, which to me as a beginner, seems redundant.
Many thanks, A.
Solution
ServletRequest is a servlet-specific type and should not be exposed to other layers of the applications.
If your services, data access objects, etc. are all bound to the ServletRequest class (i.e. they all take a ServletRequest as argument, for example), then you have two main drawbacks:
- the code is only usable in a servlet context: you can't use them in a console application, or in a web app not based on the servlet spec, or when actions are triggered by something other than a HTTP request (like a message from a queue, for example)
- the code is harder to read, understand and test
Let's take a simple example. What is the easiest to understand between these two versions of a method:
class TransferForm {
String fromAccountId;
String toAccountId;
BigDecimal amount;
// constructor, methods omitted for brevity
}
void transferMoney(TransferForm form);
or
void transferMoney(HttpServletRequest request)
How easy is it to know what you must pass as argument to both methods?
In the first case, it's extremely clear.
In the second case: where is the amount in the request? Is it a parameter? An attribute? How is it named? What type should it have? How to create and populate an instance of HttpServletRequest in your tests?
Answered By - JB Nizet