views:

1275

answers:

5

I want to intercept a request in a filter/servlet and add a few parameters to it. However, the request does not expose a 'setParameter' method and the parameter map when manipulated throws an error saying it is locked. Is there an alternative I can try?

+1  A: 

First you should receive the request and read all its parameters. Then construct another request with the original parameters + the new ones and send it again.

The HttpServletRequest is immutable and there is no way to change it.

m_pGladiator
+3  A: 

I ussualy wrap the original HttpServletRequest into a new CustomHttpServletRequest that acts as a proxy to the original request and then pass this new CustomHttpServletRequest to the filter chain.

In this CustomHttpServletRequest you can overide the getParameterNames, getParameter, getParameterMap methods to return any parameters you want.

This is an example of the filter:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequest customRequest = new CustomHttpServletRequest(httpRequest);
    customRequest.addParameter(xxx, "xxx");
    chain.doFilter(customRequest, response);
}
Panagiotis Korros
Thank you :). This worked.
Vivek Kodira
+4  A: 

Subclass HttpServletRequestWrapper and override the getParameter methods. The description of this class reads:

Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet.

In the filter, wrap the request in an instance of your subclass.

Bruno De Fraine
Thank you :). This worked.
Vivek Kodira
A: 

Otherwise, you can use the setAttribute() method which is strongly typed. Therefore, the getAttribute() method can be used ...

I'm adding this as a property-file driven mechanism that modifies a regular request. Both the UI and the actual servlet cannot be changed to accomodate these requirements - it is transparent.
Vivek Kodira
A: 

Why don't you just store variables as Request scope attributes instead of trying to append them to the request parameters?

bpapa
I'm adding this as a property-file driven mechanism that modifies a regular request. Both the UI and the actual servlet cannot be changed to accomodate these requirements - it is transparent.
Vivek Kodira