You basically need to return (forward) the request to the same JSP page with the form. You can use ${param}
to redisplay the original input. You can use request.setAttribute()
in the servlet to set some data in the request scope which you in turn can display in the JSP page.
Here's a kickoff example of such a JSP page representing a login form:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<label for="username">Username</label>
<input type="text" id="username" name="username" value="${fn:escapeXml(param.username)}">
<br>
<label for="password">Password</label>
<input type="password" id="password" name="password" value="${fn:escapeXml(param.password)}">
<br>
<span class="error">${error}</span>
(the fn:escapeXml
is mandatory to prevent from XSS attacks when redisplaying user-controlled input)
In a servlet which is postprocessing the request, you can handle the login roughly as follows:
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // User found, login it.
response.sendRedirect("home"); // Redirect to home page.
} else {
request.setAttribute("error", "Unknown username/password, please try again"); // Set message which you display in ${error}
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Redisplay the same JSP page.
}
Note that the above example displays the error embedded on the same page and is not displaying an alert, since alerts are bad user experience. If you really insist in displaying an alert, then you can grab JSTL c:if
tag to print an alert conditionally:
<c:if test="${not empty error}">
<script>alert('${error}');</script>
</c:if>
Again, this is not the normal practice.
See also: