Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

java - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...