如果从数据库中检索的用户名和密码不正确,那么我想在jsp页面本身上显示错误,而不是重定向到另一个页面。
现在,如果用户名和密码无效,我将显示验证servlet的消息。如何使用javascript或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" />
</form>
我的Validate登录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();
}
}
答案 0 :(得分:1)
您可以使用<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", "");
答案 1 :(得分:0)
在你的其他部分验证登录servlet放置此代码:
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");
}
%>