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 m
You can wrap HttpServletRequest into new HttpServletRequestWrapper object and overwrite some methods.
The following code is from http://www.ocpsoft.org/opensource/how-to-safely-add-modify-servlet-request-parameter-values/ .
To add parameter in filter:
public class MyFilter implements Filter {
...
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httprequest = (HttpServletRequest) request;
Map extraParams = new HashMap();
extraParams.put("myparamname", String[] { "myparamvalue" });
request = new WrappedRequestWithParameter(httprequest, extraParams);
}
chain.doFilter(request, response);
}
...
class WrappedRequestWithParameter extends HttpServletRequestWrapper {
private final Map modifiableParameters;
private Map allParameters = null;
public WrappedRequestWithParameter(final HttpServletRequest request, final Map additionalParams) {
super(request);
modifiableParameters = new TreeMap();
modifiableParameters.putAll(additionalParams);
}
@Override
public String getParameter(final String name) {
String[] strings = getParameterMap().get(name);
if (strings != null) {
return strings[0];
}
return super.getParameter(name);
}
@Override
public Map getParameterMap() {
if (allParameters == null) {
allParameters = new TreeMap();
allParameters.putAll(super.getParameterMap());
allParameters.putAll(modifiableParameters);
}
// Return an unmodifiable collection because we need to uphold the interface contract.
return Collections.unmodifiableMap(allParameters);
}
@Override
public Enumeration getParameterNames() {
return Collections.enumeration(getParameterMap().keySet());
}
@Override
public String[] getParameterValues(final String name) {
return getParameterMap().get(name);
}
}
}