views:

1569

answers:

3

I am using a javax.servlet.http.HttpServletRequest to implement a web application.

I have no problem to get the parameter of a request using the getParameter method. However I don't know how to set a parameter in my request.

+3  A: 

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.

skaffman
+5  A: 

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);
MaurizioPz
Attributes and parameters are not interchangeable, and represent very different concepts.
skaffman
@skaffman but perhaps he can solve what he needs using attributes - there should be no need to add a new parameter to a request in the middle of processing the request
matt b
the answer should be edited to reflect that setting an attribute might be a solution to the problem, instead of implying setting the attribute sets a parameter in the request.
Chii
Sorry if my question wasn't sufficiently clear, but what I really wanted to know was if it was possible to set a parameter and not an attribute, that's why I accepted skaffman answer. However, your answer is good and probably will help someone else :-)
Alceu Costa
no problem...just out of curiosity... why would you need to set a parameter?thanks
MaurizioPz
+2  A: 

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

}

Jeff Williams