Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we wrap HttpServletRequest ? The api provides an HttpServletRequestWrapper but what do we gain from wrapping the request?

What is the purpose of wrapping an HttpServletRequest using an HttpServletRequestWrapper ? What benefits do we gain from doing this ?

like image 824
Ankit Goel Avatar asked May 25 '17 13:05

Ankit Goel


People also ask

What is the use of HttpServletRequestWrapper?

Class HttpServletRequestWrapper. Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet. This class implements the Wrapper or Decorator pattern. Methods default to calling through to the wrapped request object.

What is the difference between HttpServletRequest and ServletRequest?

ServletRequest provides basic setter and getter methods for requesting a Servlet, but it doesn't specify how to communicate. HttpServletRequest extends the Interface with getters for HTTP-communication (which is of course the most common way for communicating since Servlets mostly generate HTML).

Which method of the HttpServletRequest object is used to get the value?

getParameter() − You call request. getParameter() method to get the value of a form parameter.

How do I read HttpServletRequest multiple times?

Then, we created a new implementation of the HttpServletRequestWrapper class. We overrode the getInputStream() method to return an object of ServletInputStream class. Finally, we created a new filter to pass the request wrapper object to the filter chain. So, we were able to read the request multiple times.


1 Answers

HttpServletRequest is an interface for a HTTP specific servlet request. Typically you get instances of this interface in servlet filters or servlets.

Sometimes you want to adjust the original request at some point. With a HttpServletRequestWrapper you can wrap the original request and overwrite some methods so that it behaves slightly different.

Example:

You have a bunch of servlets and JSPs which expect some request parameters in a certain format. E.g. dates in format yyyy-MM-dd.

Now it is required to support the dates also in a different format, like dd.MM.yyyy with the same functionality. Assuming there is no central string to date function (it's an inherited legacy application), you have to find all places in the servlets and JSPs.

As an alternative you can implement a servlet filter. You map the filter so that all requests to your servlets and JSPs will go through this filter.

The filter's purpose is to check the date parameters' format and reformat them to the old format if necessary. The servlets and JSPs get the date fields always in the expected old format. No need to change them.

This is the skeleton of your filter:

public void doFilter(ServletRequest request, ServletResponse response, 
    FilterChain chain) throws IOException, ServletException {
  HttpServletRequest adjustedRequest = adjustParamDates((HttpServletRequest) request);
  chain.doFilter(adjustedRequest, response);
}

We take the original request and in method adjustParamDates() we manipulate the request and pass it down the filter chain.

Now, how would we implement adjustParamDates()?

private HttpServletRequest adjustParamDates(HttpServletRequest req) {
  // ???
}

We need a new instance of interface HttpServletRequest which behaves exactly like the original instance req. But the four methods getParameter(), getParameterMap(), getParameterNames(), getParameterValues() shouldn't work on the original parameters but on the adjusted parameter set. All other methods of interface HttpServletRequest should behave like the original methods.

So we can do something like that. We create an instance of HttpServletRequest and implement all methods. Most method implementations are very simple by calling the corresponding method of the original request instance:

private HttpServletRequest adjustParamDates(final HttpServletRequest req) {
  final Map<String, String[]> adjustedParams = reformatDates(req.getParameterMap());
  return new HttpServletRequest() {
    public boolean authenticate(HttpServletResponse response) {
      return req.authenticate(response);
    }

    public String changeSessionId() {
      return req.changeSessionId();
    }

    public String getContextPath() {
      return req.getContextPath();
    }

    // Implement >50 other wrapper methods
    // ...

    // Now the methods with different behaviour:
    public String getParameter(String name) {
      return adjustedParams.get(name) == null ? null : adjustedParams.get(name)[0];
    }

    public Map<String, String[]> getParameterMap() {
      return adjustedParams;
    }

    public Enumeration<String> getParameterNames() {
      return Collections.enumeration(adjustedParams.keySet());
    }

    public String[] getParameterValues(String name) {
      return adjustedParams.get(name);
    }
  });
}

There are more than 50 methods to implement. Most of them are only wrapper implementations to the original request. We need only four custom implementations. But we have to write down all these methods.

So here comes the class HttpServletRequestWrapper into account. This is a default wrapper implementation which takes the original request instance and implements all methods of interface HttpServletRequest as simple wrapper methods calling the corresponding method of the original request, just as we did above.

By subclassing HttpServletRequestWrapper we only have to overwrite the four param methods with custom behaviour.

private HttpServletRequest adjustParamDates(final HttpServletRequest req) {
  final Map<String, String[]> adjustedParams = reformatDates(req.getParameterMap());
  return new HttpServletRequestWrapper(req) {
    public String getParameter(String name) {
      return adjustedParams.get(name) == null ? null : adjustedParams.get(name)[0];
    }

    public Map<String, String[]> getParameterMap() {
      return adjustedParams;
    }

    public Enumeration<String> getParameterNames() {
      return Collections.enumeration(adjustedParams.keySet());
    }

    public String[] getParameterValues(String name) {
      return adjustedParams.get(name);
    }
  });
}
like image 64
vanje Avatar answered Nov 15 '22 21:11

vanje