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?
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.
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.
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With