When I'm done processing in a servlet, and the result is valid, then I need to redirect the response to another JSP page, say welcome.jsp
in web content folder. How can I do it?
For example:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // Some processing code here ... // How do I redirect to another JSP here when I'm ready? } catch (Exception e) { throw new ServletException(e); } }
For redirect a page in JSP, we are calling response. sendRedirect(), By using this method, the server return back the response to the client, from where next request comes and it displays that url. Here we are using the implicit object "response" to redirect the browser to a different resource.
forward() method This method forwards a request from a servlet to another servlet on the same server. It allows one servlet to do the initial processing of a request, obtains the RequestDispatcher object, and forwards the request to another servlet to generate the response.
To forward a request from one page to another JSP page we can use the <jsp:forward> action. This action has a page attribute where we can specify the target page of the forward action. If we want to pass parameter to another page we can include a <jsp:param> in the forward action.
Look at the HttpServletResponse#sendRedirect(String location)
method.
Use it as:
response.sendRedirect(request.getContextPath() + "/welcome.jsp")
Alternatively, look at HttpServletResponse#setHeader(String name, String value)
method.
The redirection is set by adding the location header:
response.setHeader("Location", request.getContextPath() + "/welcome.jsp");
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