重定向验证[英] Validation on Redirect

问题描述

验证.java

     try
    {
        conn = dsEvent.getConnection();
        String userCheck = "select * from customer";
        stmt = conn.createStatement();
        rs = stmt.executeQuery(userCheck);
        while(rs.next()){
           if((email.equals(rs.getString("email")))&&(password.equals(rs.getString("password"))))
           {
               RequestDispatcher rd = req.getRequestDispatcher("/success.jsp");
               rd.forward(req,res);
           }
           else
           {
              req.getSession().setAttribute("error", "The email or password you entered is incorrect. Please try again");
            res.sendRedirect(this.getServletContext().getContextPath() + "/index.jsp");
           }
        }
    } catch (SQLException ex) {
        System.err.println(ex);
    }
}

index.jsp

  <body>
    <h2>System</h2>
    <p style ="color:red"><%=session.getAttribute("error")!=null ? "":session.getAttribute("error") %></p>
    <form method ="post" action="validation">
        Please Login: <br/>
        Email: <input type="email" name="email" required/><br/>
        Password: <input type="password" name="password" required/><br/>
        <input type ="submit" value="Login"/>
    </form>
</body>

我正在验证电子邮件和密码.因此,当用户输入正确的电子邮件和密码时,它将转发到 success.jsp.如果用户输入错误的详细信息,它会将页面与错误一起重定向到 index.jsp.

但我似乎无法让它在错误的细节部分上工作.它给了我

<块引用>

警告:StandardWrapperValve[com.events.ValidationServlet]:PWC1406:Servlet.service() 为 servlet com.events.ValidationServlet 抛出异常

推荐答案

为什么要遍历整个 resultset 并验证用户是否存在,而不是尝试更改 select 查询以检查特定用户是否存在你的数据库与否.

要做到这一点,请尝试下面的代码

String email = request.getParameter("email");
String password = request.getParameter("password");
String userCheck = "select * from tableName where username = ? AND password = ?";
PreparedStatement ps = con.prepareStatement(userCheck);
ps.setString(1, email);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();

而不仅仅是检查 resultset 是否为空.

检查结果集是否为空或未放入以下代码:

if(rs.isBeforeFirst()) {
    request.getSession().setAttribute("email",email);
    response.sendRedirect("success.jsp");
} else {
    request.setAttribute("error", "Invalid Username & Password");
    request.getRequestDispatcher("index.jsp").forward(request, response);
}

isBeforeFirst() 方法请看这里.

同时更改 index.jsp 以显示错误消息

<p style ="color:red"><%=request.getAttribute("error")!=null ? request.getAttribute("error"): "" %></p>

本文地址:https://www.itbaoku.cn/post/978593.html