JSP Forward vs. Redirect and Browser URL
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 开发者_JS百科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.
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.
精彩评论