mysql—错误;java.lang.illegalstateexception:提交响应后无法创建会话

e0bqpujr  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(569)

这个问题在这里已经有答案了

java.lang.illegalstateexception:提交响应后无法创建会话(2个答案)
两年前关门了。
我正在尝试使用mysql为javaweb应用程序创建一个登录页。当我运行代码时,我收到这个异常;java.lang.illegalstateexception:提交响应后无法创建会话

protected void processRequest(HttpServletRequest request,  HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
        `String email = request.getParameter("email");
        String pass = request.getParameter("pass");
        MyDb1 db = new MyDb1();
      Connection con = db.getCon();
      Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery("select uid,email,pass from register where email = '"+email+"' and  pass = '"+pass+"'");
    if ((rs.next())) {

        String uid = rs.getString("uid");
        response.sendRedirect("http://localhost:8080/FinalYearProjec/userprofile.jsp");  

          HttpSession session=request.getSession();  
          session.setAttribute("name",uid); } 

else {
  RequestDispatcher rd = request.getRequestDispatcher("/Incorrect.html");
                rd.forward(request, response);

 }

  } catch (SQLException ex) {
    Logger.getLogger(Logi.class.getName()).log(Level.SEVERE,   null, ex);
         }
cigdeys3

cigdeys31#

您的错误是因为在设置会话属性之前正在重定向:

response.sendRedirect("http://localhost:8080/FinalYearProjec/userprofile.jsp");  

  HttpSession session=request.getSession();  
  session.setAttribute("name",uid); }

无论何时将用户重定向或转发到其他页面,都需要确保在转发或重定向之前执行了任何操作。所以就这样改变它:

HttpSession session=request.getSession();  
  session.setAttribute("name",uid); } 

 response.sendRedirect("http://localhost:8080/FinalYearProjec/userprofile.jsp");  //put this last

下面是清理过的代码,以及不需要的内容(在这里使用preparedstatement,因为手动构建语句并不安全,正如前面提到的注解一样)

protected void processRequest(HttpServletRequest request,  HttpServletResponse response) throws ServletException, IOException {
    String email = request.getParameter("email");
    String pass = request.getParameter("pass");
    MyDb1 db = new MyDb1();

    String url = "Incorrect.html";    
    try(Connection con = db.getCon()){

         PreparedStatement pst = con.prepareStatement("select uid,email,pass from register where email = ? and pass = ?;"); 
         pst.setString(1, email); //set first '?'
         pst.setString(2, pass); //set second '?'
         ResultSet rs = pst.executeQuery();

        while(rs.next()) {

            url = "userprofile.jsp"; //override url string

            String uid = rs.getString("uid");

            HttpSession session=request.getSession();  
            session.setAttribute("name",uid); 

        }

    } catch (SQLException e) {
        e.printStackTrace();
    }

    RequestDispatcher rd = request.getRequestDispatcher(url);
    rd.forward(request, response);

}

相关问题