How to pass a request parameter from one servlet to a other while forwaring

Gabriel Glenn picture Gabriel Glenn · Feb 19, 2014 · Viewed 33.7k times · Source

There is my goal that I can't achieve for now :

I have one servlet, say 'ReportServlet'. It takes a request parameter, say 'p'. I can obviously get the parameter by :

 request.getParameter("p");

The query string in my JSP is :

<a href="<c:url value="/report"/>?p=value">report</a>

And everythings works fine.

Now : I have another servlet, say 'PreProcessingServlet'. I want to forward PreProcessingServlet to ReportServlet, passing a 'p' parameter which is computed in PreProcessingServlet. I tried :

RequestDispatcher rd = getServletContext().getRequestDispatcher("/report?p="+value);
rd.forward(request, response);   

But the parameter 'p' goes in the request's queryString member, not in the parameters.

How can I pass the 'p' parameter, using query parameter in the way that I can retrieve 'p' the same way from the JSP and from the forward.

I don't want to use a request attribute because I want a unique solution to get the parameter from both a JSP and a forward.

I guess I'm missing something, but I can't find what !

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Feb 20, 2014

When in doubt, always go to the specification. In this case, see chapter 9.1.1 Query Strings in Request Dispatcher Paths

The ServletContext and ServletRequest methods that create RequestDispatcher objects using path information allow the optional attachment of query string information to the path. For example, a Developer may obtain a RequestDispatcher by using the following code:

String path = "/raisins.jsp?orderno=5"; 
RequestDispatcher rd = context.getRequestDispatcher(path);    
rd.include(request, response);

Parameters specified in the query string used to create the RequestDispatcher take precedence over other parameters of the same name passed to the included servlet. The parameters associated with a RequestDispatcher are scoped to apply only for the duration of the include or forward call.

So you can very well do

RequestDispatcher rd = getServletContext().getRequestDispatcher("/report?p="+value);
rd.forward(request, response);   

And the parameter p will be available only for HttpServletRequest that is given to the resource mapped to handle the specified path, ie. /report in this case. If that is a HttpServlet, you can then access it with

request.getParameter("p");

where request would be the HttpServletRequest method parameter.

When the forward(..) call terminates and execution comes back to your PreProcessingServlet, the parameter will no longer be available in the local HttpServletRequest object.