25

I want to add a new parameter to the parameter map of my HttpServletRequest.

The following code

 request().getParameterMap().put("j_username", user);
 request().getParameterMap().put("j_password", pwd);

creates this error

no modifications are allowed to a locked parameter map

What is the correct way to do this?

JoshDM
  • 4,939
  • 7
  • 43
  • 72
M Sach
  • 33,416
  • 76
  • 221
  • 314

2 Answers2

22

The parameters of a request are the values sent as parameters by the browser. There is no reason to change them. If you want to associate some value to the request, use an attribute rather than a parameter. This has the additional advantage that an attribute may be any object and not just a String:

request.setAttribute("user", new User(userName, password));

You may add parameters if you forward the request to another resource (although I wouldn't say it's a good practice):

request.getRequestDispatcher("/some/path?j_username=" + user + "&j_password=" + pwd).forward(request, response);

The parameters should be encoded correctly, though.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 4
    Actually i want to add parameter not attribute in request. Reason is i am working on extenssion of some open source application (xwiki) to suit my needs which expects a parameter in request and the way it is getting is request.getParameter("paramName"); Original request is coming from another webapplication which i cant set there itself as it does not have knowledge of them – M Sach Dec 18 '11 at 11:26
  • Then the link provided by mucayufa is probably what you're looking for. I don't think you'll be able to authenticate like this, though. – JB Nizet Dec 18 '11 at 11:31
  • 3
    There is a good article on this here: http://ocpsoft.org/opensource/how-to-safely-add-modify-servlet-request-parameter-values/ – Lincoln Apr 10 '13 at 15:10
9

I ran into a similar issue and got around it by making a copy of the parameter map.

Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());
Greg Prisament
  • 2,166
  • 1
  • 17
  • 18