Reputation: 485
Is it possible to change the Servlet request object while forwarding the request from one servlet to another? or a work around for achieving this?
I have 2 servlet's, Servlet1 and Servlet2 like for e.g. -
public class Servlet1 extends HttpServlet {
doPost(HttpServletRequest rq, HttpServletResponse rs) {
// do something meaningful, call other different web-apps/servlets
InputStream is1 = rq.getInputStream();
RequestDispatcher rd = getServletContext().getRequestDispatcher("/Servlet2");
rd.forward(rq, rs);
}
}
If I print the is1
it is something like -
-----Part2_324<?xml version="1.0" encoding="utf-8"?><Head><Body><Text>This is the first File</Text></Body></Head>-------Part2_65623
I dont care about this o/p, when later the request is to be forwarded to the Servlet2
.
I have an xml file file2.xml, contents are -
<?xml version="1.0" encoding="utf-8"?><Head><Body><Top>Start</Top><Middle>Process</Middle><Bottom>End</Bottom></Body></Head>
I would like this to be as the request content for the Servlet2
, as it cannot process the contents of is1
, it is meant to be processing content of file2.xml.
There are pretty much no Attributes/Parameters set.
Is it possible to achieve this? I hope, the question is clear.
Thank you
Upvotes: 2
Views: 4110
Reputation: 403611
The servlet spec forbids the substitution of one request for another when forwarding.
However, it does permit the forwarding of an HttpServletRequestWrapper
, where the wrapper is wrapping the original request. So try and implement your logic as a subclass of HttpServletRequestWrapper
, wrapping the original request, and overriding the various methods of HttpServletRequest
as appropriate.
Upvotes: 8