How to call another servlet in a servlet?

As indicated, how do I invoke another servlet in the servlet and get the called servlet response?

0
source share
4 answers

Use the RequestDispatcher instance available through the HttpServletRequest instance.

However, if you want to access a single instance stored in a servlet container [for example, using the getServlet method on an instance of ServletContext ], this is a completely different story. Servlet specifications purposefully reject an operation that might allow such an option. But if you really want to call one servlet while executing another, use the include method of RequestDispatcher instead of the forward method.

+3
source

Look here:

 getServletContext().getNamedRequestDispatcher("servletName") .forward(request, response); 

However, I would suggest that there are better options. For example, move the code needed for the helper class / utility and call it.

As I think about it, you may need something else: call the servlet separately. For this you need:

 InputStream is = new URL(urlOfTheServlet).openStream(); IOUtils.copy(is, response.getOutputStream()); 

(this uses apache commons-io to copy the input stream to the output stream of the current request)

+1
source

Use ServletContext or the current request to receive RequestDispatcher, and then use RequestDispatcher forward () or include ().

You can use Spring MockHttpServletRequest and MockHttpServletResponse to create a new request and response instead of using the current request.

Example:

 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); RequestDispatcher dispatcher = request.getRequestDispatcher(url); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.setServerName(request.getServerName() ); servletRequest.setServerPort(request.getServerPort() ); servletRequest.setSession(request.getSession() ); servletRequest.setMethod(HttpMethod.GET.name() ); servletRequest.setRequestURI(url); servletRequest.setParameters(parameters); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); servletResponse.setCharacterEncoding("UTF-8"); // Use include() instead of forward(). Similar as client HttpClient GET dispatcher.include(servletRequest, servletResponse); String content = servletResponse.getContentAsString(); 
0
source
 String destinationBlockAccount ="./BlockAccount"; response.sendRedirect(response.encodeRedirectURL(destinationBlockAccount)); 

Alternatively, you can send a parameter such as directly from JSP:

 response.sendRedirect(response.encodeRedirectURL("./GetAccount?accountID="+accountID)); 
0
source

All Articles