How to set a parameter in a HttpServletRequest?
You can't, not using the standard API. HttpServletRequest
represent a request received by the server, and so adding new parameters is not a valid option (as far as the API is concerned).
You could in principle implement a subclass of HttpServletRequestWrapper
which wraps the original request, and intercepts the getParameter()
methods, and pass the wrapped request on when you forward.
If you go this route, you should use a Filter
to replace your HttpServletRequest
with a HttpServletRequestWrapper
:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (servletRequest instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) servletRequest;
// Check wether the current request needs to be able to support the body to be read multiple times
if (MULTI_READ_HTTP_METHODS.contains(request.getMethod())) {
// Override current HttpServletRequest with custom implementation
filterChain.doFilter(new HttpServletRequestWrapper(request), servletResponse);
return;
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
If you really want to do this, create an HttpServletRequestWrapper.
public class AddableHttpRequest extends HttpServletRequestWrapper {
private HashMap params = new HashMap();
public AddableingHttpRequest(HttpServletRequest request) {
super(request);
}
public String getParameter(String name) {
// if we added one, return that one
if ( params.get( name ) != null ) {
return params.get( name );
}
// otherwise return what's in the original request
HttpServletRequest req = (HttpServletRequest) super.getRequest();
return validate( name, req.getParameter( name ) );
}
public void addParameter( String name, String value ) {
params.put( name, value );
}
}
From your question, I think what you are trying to do is to store something (an object, a string...) to foward it then to another servlet, using RequestDispatcher(). To do this you don't need to set a paramater but an attribute using
void setAttribute(String name, Object o);
and then
Object getAttribute(String name);