Validation on Redirect

后端 未结 3 1978
死守一世寂寞
死守一世寂寞 2021-01-17 05:28

validation.java

     try
    {
        conn = dsEvent.getConnection();
        String userCheck = \"select * from customer\";
        stmt = conn.createState         


        
3条回答
  •  孤独总比滥情好
    2021-01-17 06:07

    This is mainly an addition to Luiggi Mendoza's answer. You cannot have forward or sendRedirect inside a loop except if you pass only once in the loop. As you have, the servlet throws an exception what is causing your error.

    You could move those codes outside the loop :

        boolean found = false;
        while( (! found) && rs.next()){
           if((email.equals(rs.getString("email")))&&(password.equals(rs.getString("password"))))
           {
               found = true;
           }
        }
        if (found) {
           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");
        }
    

    But here you are looping by hand on a resultset, when you could let the database find if there is a match :

        conn = dsEvent.getConnection();
        String userCheck = "select count(*) from customer where email = ? and password = ?";
        stmt = conn.prepareStatement();
        stmt.setString(1, email);
        stmt.setString(2, password);
        rs = stmt.executeQuery(userCheck);
        if (rs.next().getInt(1) > 0) 
           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");
        }
    

提交回复
热议问题