Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a parameter in a HttpServletRequest?

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.

like image 944
Alceu Costa Avatar asked May 21 '09 11:05

Alceu Costa


People also ask

What are HttpServletRequest parameters?

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.

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.

How do I pass HttpServletRequest in Java?

Pass it to the constructor: public class XmlParser{ final private HttpServletRequest request; public XmlParser(HttpServletRequest request) { this. request = request; } // use it in othe methods... }

Which are the two parameters of Httpservlet?

The first two are parameters, and the third a throws list. The first parameter to this method ( HttpServletRequest req) is an object representing the request made by the browser.


1 Answers

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); } 
like image 87
skaffman Avatar answered Oct 06 '22 03:10

skaffman