Reputation: 1558
I have a basic login form that asks for a username and password. The information is passed to a servlet, but if it's invalid I want the servlet to redirect back to the login page.
At the moment the servlet is doing this:
else{
request.setAttribute("error","Username or password incorrect");
request.getRequestDispatcher("Login.jsp").forward(request, response);
}
I need that error
attribute to be set so that I can have an alert on the login page when the user is redirected back there:
<div style="color: red">${error}</div>
While a valid login is fine, an invalid one sits on /LoginServlet?user=test&pswd=test
, whereas I want it to simply sit on /Login.jsp
I know that this is because I'm using forward
instead of response.sendRedirect
(I use this for a valid logon), but using the latter causes me to loose my error
attribute.
Is there anyway around this?
Upvotes: 2
Views: 3773
Reputation: 11140
Your assertion of forward vs actual redirect and the limited scope of request attributes is correct. You could make your error thing a Session attribute, which would let you reference it from Login.jsp on the redirect, but now you have the added problem of clearing it once you use it to render Login.jsp. Its not horrible, but just another thing you need to remember to do.
Rock, hard place. The problem with the URL not being Login.jsp on the error case is what?
Upvotes: 0
Reputation: 280102
Yes, there is a workaround, but it requires extra functionality. What you are describing is known as the Flash Scope. We want to keep an attribute so that it is available in the next request. This is usually done in POST-REDIRECT-GET scenarios.
The Servlet API doesn't have such functionality so we have to implement it ourselves. You can do it with a Filter
as described here.
Basically, you add the attribute to the HttpSession
on your first request. On the next one, you copy it from the HttpSession
into the HttpServletRequest
attributes and clear it from the HttpSession
.
Upvotes: 3