Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending redirect to another servlet/JSP without loosing the request parameters.

Tags:

java

jsp

servlets

How do i specify a redirection to another servlet, in the doPost() method of a servlet.

at the moment I'm using

request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);

which is wrong since, my parameters in the doGet() method of products are not being called and initialized.

So I'm left with an empty products page after logging in :/

like image 533
user478636 Avatar asked Apr 04 '11 13:04

user478636


People also ask

Can a servlet redirect to another servlet?

The sendRedirect() method works at client side. It sends the same request and response objects to another servlet. It always sends a new request. It can work within the server only.

How would you forward a request to another servlet or JSP page from a JSP page?

When dynamically including or forwarding to a servlet from a JSP page, you can use a jsp:param tag to pass data to the servlet (the same as when including or forwarding to another JSP page). For more information about the jsp:param tag, see "JSP Actions and the <jsp: > Tag Set".

What is the difference between forward and sendRedirect tag in JSP?

The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens at server end and not visible to client, but in case of sendRedirect(), redirection happens at client end and it's visible to client.


2 Answers

You need to use HttpServletResponse#sendRedirect() to send a redirect. Assuming that the servlet is mapped on an URL pattern of /products:

response.sendRedirect("/products");

This way the webbrowser will be instructed to fire a new HTTP GET request on the given URL and thus the doGet() method of the servlet instance will be called where you can in turn load the products and forward to a JSP which displays them the usual way.

like image 176
BalusC Avatar answered Sep 30 '22 09:09

BalusC


In your doPost you can always call:

return doGet(request, response);
like image 33
El Guapo Avatar answered Sep 30 '22 10:09

El Guapo