我有一个用户登录表单,当密码与数据库中的密码不匹配时会出现一条错误消息。我将错误消息重定向到如下所示的表单,但是当它在表单上显示错误消息时,它将删除电子邮件/密码输入字段中的数据。显示错误消息后如何将数据仍保留在输入字段中?先感谢您。
//将服务重定向到JSP
request.setAttribute("errorMessage", "Wrong credentials!"); request.getRequestDispatcher("/Login.jsp").forward(request, response);
// JSP表单页
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <title>User Log in</title> </head> <body> <form action = "LoginServlet" method="POST"> <h3>Sign In</h3><br> Email: <input type="text" name="email" required><br> Password: <input type="password" name="pass" required><br> <div style="color: #FF0000;">${errorMessage}</div><br> <input type="submit" name="submit" value="Sign in"> </form> </body> </html>
我通过添加以下几行来解决此问题:
// SERVLET
request.setAttribute("email",request.getParameter("email")); request.setAttribute("pass", request.getParameter("pass")); request.setAttribute("errorMessage", "Wrong credentials!"); request.getRequestDispatcher("/Login.jsp").forward(request, response);
// JSP页面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <title>User Log in</title> <%@ include file="PageHeader.html" %> </head> <body> <form action = "LoginServlet" method="POST"> <h3>Sign In</h3><br> Email: <input type="text" name="email" required value="${email}"><br> Password: <input type="password" name="pass" required value="${pass}"><br> <div style="color: #FF0000;">${errorMessage}</div><br> <input type="submit" name="submit" value="Sign in" id="sButton"> </form> </body> </html>