views:

31

answers:

1

I have a case where I need to redirect my HTTP request object to other controllers/classes for further processing. The problem is that in some controller, I would like to get better control on the parameters I'm forwarding to the next class: modify, edit, remove them. So, I would like to know if there is a good practice/pattern to achieve this basic control on the HTTP request parameters.

+2  A: 

The good practice is to wrap the request object in another object using a servlet filter. Since HttpServletRequest is an interface, you can write your own implementation of it. Your implementation can hold the request you received and delegate any and all of its own methods to the original request object, but also modify the return values as you see fit. So your getParameter() etc. methods could call the same method on the original request object, and modify the result as you see fit before returning it.

class MyHttpServletRequestWrapper implements HttpServletRequest {
   private HttpServletRequest originalRequest;

   public MyHttpServletRequestWrapper(HttpServletRequest originalRequest) {
      this.originalRequest = originalRequest;

   public String getAuthType() {return originalRequest.getAuthType();}
   public String getQueryString() {return originalRequest.getQueryString();}
   // etc.

   public Map getParameterMap() {
      Map params = originalRequest.getParameterMap();
      params.remove("parameter-to-remove");
      params.put("parameter-to-add", "<a value>");
      //etc.
   }
}

Your servlet filter:

class MyFilter implements Filter {
    public void init(FilterConfig config) {
       // perhaps you might want to initialize something here
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        HttpServletRequest originalRequest = (HttpServletRequest) request;
        HttpServletRequest newRequest = new MyHttpServletRequest(originalRequest);
        chain.doFilter(newRequest, response);
    }
}

You can also subclass javax.servlet.request.HttpServletRequestWrapper, which will save you a bunch of work.

See this post for more.

Ladlestein
Even though the post you link to contains more information, you should specify that this should be done using a filter (if that is what you meant).
vetler
thanks a lot. i will use the filters and the wrapper class for the HttpRequest object.
work.paul