2

I have an issue with a JSP/Servlet set-up and what's getting displayed in the browser URL. page1.jsp submits to the servlet by a form with an action of "SAVE.do". The servlet wants to pass a success message back to page1.jsp on the save. I do this by placing the message in the request using the

request.setAttribute("message", "Save Successful");

I then call

request.getRequestDispatcher("page1.jsp").forward(req,resp);

However, the browser will display the URL of http://localhost:8080/SAVE.do instead of http://localhost:8080/page1.jsp

When I change the forward to a redirect using

response.sendRedirect("page1.jsp");

Then the attribute is lost.

I guess I'm looking for the right way to do this, so that I can get the attribute back when page1.jsp loads again, WITH the right URL displaying in the browser.

bluedevil2k
  • 9,366
  • 8
  • 43
  • 57
  • Related (not exactly a dupe): http://stackoverflow.com/questions/6068891/difference-between-jsp-forward-and-redirect – BalusC Oct 11 '11 at 14:42

1 Answers1

8

The right URL is the one the browser submitted to. The fact that the request is first handled by a servlet and then by a JSP is irrelevant to the browser. BTW, the JSP could very well be in a protected folder (like /WEB-INF), since the browser never sends a request to this JSP directly, but does through the URL of the dispatcher servlet.

A redirect is a totally different thing than a forward. Forward means : I use another server component to finish the handling of my request. Redirect means : I have finished handling the request, and I'll ask the browser to go visit another URL, and thus make a new request. This new URL could be a totally external URL (google.com for example).

In your situation, you might want to apply the post-redirect-get pattern, so that a refresh of the "success" page doesn't trigger the re-submission of the form. But if you want to display a dynamically chosen message, you'll have to save it into the session and retrieve it in the second request. Your second request should go through a servlet as well, though, if you want to apply the MVC pattern correctly.

Note that most MVC frameworks have suppport for the post-redirect-get pattern.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255