如果从数据库中检索到的用户名和密码不正确,那么我会在jsp页面本身显示错误,而不是重定向到另一个页面。
现在,如果用户名和密码无效,我会显示一条来自验证servlet的消息。如何在jsp视图中使用javascript或任何其他工具在前端显示消息?
以下是我的登录表:
<form id="loginform" class="form-horizontal" name="myForm" method="POST" action="ValidateLoginServlet2.do" onSubmit="return validateLogin()">
<input type="text" class="form-control" name="uname" placeholder="username">
<input id="login-password" type="password" class="form-control" name="pwd" placeholder="password">
<input type="submit" value="Login" href="#" class="btn btn-success" />
</form>和我的验证登录servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
PrintWriter out = response.getWriter();
String username = request.getParameter("uname");
String password = request.getParameter("pwd");
System.out.println(username);
System.out.println(password);
try
{
Connection con = OracleDBConnection.getConnection();
PreparedStatement statement = con.prepareStatement("select firstname, password from registration where firstname =? and password=?");
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
if(result.next()){
response.sendRedirect("LoginSuccessful.jsp");
}else{
out.println("username and password are incorrect");
}
}catch(Exception e){
System.out.println("DB related Error");
e.printStackTrace();
}
}发布于 2015-06-11 00:08:25
您可以使用<span>元素来显示从servlet request获得的错误消息,下面是JSP页面:
<form id="loginform" class="form-horizontal" name="myForm" method="POST" action="ValidateLoginServlet2.do" onSubmit="return validateLogin()">
<input type="text" class="form-control" name="uname" placeholder="username">
<input id="login-password" type="password" class="form-control" name="pwd" placeholder="password">
<input type="submit" value="Login" href="#" class="btn btn-success" />
<span style="color:red;">${errMsg}</span>
</form>在servlet中,您可以在else语句中设置一个错误消息,如下所示:
if(result.next()) {
response.sendRedirect("LoginSuccessful.jsp");
}else{
request.setAttribute("errMsg", "username and password are incorrect");
// The following will keep you in the login page
RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
rd.forward(request, response);
}为了防止下次在if块中成功登录时显示相同的错误,您可以像这样重置ErrMsg:
request.setAttribute("errMsg", "");发布于 2015-06-10 23:27:27
在验证登录servlet的else部分中,放入以下代码:
if(result.next()){
response.sendRedirect("LoginSuccessful.jsp");
}
else{
HttpSession session = request.getSession();
session.setAttribute("wrong_uname_pass", "1");
response.sendRedirect("index.jsp");
}并将以下代码放在index.jsp的第一部分(或者在哪里是您的登录表单)
<%
if(session.getAttribute("wrong_uname_pass") != null){
%>
<script>
alert("wrong user name or password");
</script>
<%
session.removeAttribute("wrong_uname_pass");
}
%>https://stackoverflow.com/questions/30760421
复制相似问题