Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send redirect to JSP page in Servlet

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);     } } 
like image 709
SaM Avatar asked Nov 29 '12 08:11

SaM


People also ask

How can I redirect one page to another page in JSP?

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.

How do I redirect one servlet to another?

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.

How do I forward a request in JSP?

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.


1 Answers

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"); 
like image 135
px1mp Avatar answered Sep 17 '22 14:09

px1mp