Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a parameter to the existing HttpServletRequest of my Java Servlet?

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?

like image 999
M Sach Avatar asked Dec 18 '11 11:12

M Sach


People also ask

How do you add a parameter to a Java request?

HttpRequest. Builder helps us to easily create HTTP requests and add parameters using the builder pattern. The Java HttpClient API does not provide any methods to add query parameters.

How can we send parameters to a servlet?

You can pass parameters to an HTTP servlet during initialization by defining these parameters in the Web application containing the servlet. You can use these parameters to pass values to your servlet every time the servlet is initialized without having to rewrite the servlet.

How do I edit HttpServletRequest?

You can't change the request, but you could wrap it. See the following question for more details: Why do we wrap HttpServletRequest ? The api provides an HttpServletRequestWrapper but what do we gain from wrapping the request? You will need to put a servlet filter in front of your servlet to make the wrapping work.

What are the parameters in HttpServletRequest?

Parameters. The HttpServletRequest provides methods for accessing parameters of a request. The type of the request determines where the parameters come from. In most implementations, a GET request takes the parameters from the query string, while a POST request takes the parameters from the posted arguments.


2 Answers

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.

like image 113
JB Nizet Avatar answered Oct 03 '22 04:10

JB Nizet


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());
like image 42
Greg Prisament Avatar answered Oct 03 '22 04:10

Greg Prisament