我在JSP中创建 loginpage.jsp :
<form method="post" action="login">
<input type="text" name="username">
<input type="password" name=password">
<input type="submit" value="Send">
<div id="authFail"></div> </form>
如果用户登录失败,服务器将调度员返回登录页面并显示文本“登录失败”。然后,我创建一个servlet作为登录控制器:
@Override
public void doPost(HttpServletRequest request, HttpSevletResponse response
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("name");
String password = request.getParameter("password");
if (username.equals("admin") && password.equals("root")) {
request.getRequestDispatcher("homepage.jsp").include(request, response);
} else {
request.getRequestDispatcher("loginpage.jsp").include(request, response);
out.print("document.getElementById(\"authFail\").innerHTML=\"Login Failed!!!\"");
}
}
问题: 当用户登录失败并将其发送回登录页面但未显示文本“登录失败!!! 我已经在web.xml中将我的servlet配置为url模式“login”。
答案 0 :(得分:0)
嗨,你可以这样做
@Override
public void doPost(HttpServletRequest request, HttpSevletResponse response
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("name");
String password = request.getParameter("password");
if (username.equals("admin") && password.equals("root")) {
request.getRequestDispatcher("homepage.jsp").include(request, response);
} else {
request.setAttribute("errorMessage", "Login Failed");
request.getRequestDispatcher("loginpage.jsp").include(request, response);
}
}
并以表格
<form method="post" action="login">
<div>${errorMessage}</div>
<input type="text" name="username">
<input type="password" name=password">
<input type="submit" value="Send">
<div id="authFail"></div>
为了更好的结果,请使用JSTL
<c:if test="${not empty errorMessage}">
<c:out value="${errorMessage}"/>
</c:if>
要使用JSTL,您必须将此代码添加到jsp文件
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<pre class="prettyprint">