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



我正在尝试使用MySQL为一个java web应用程序创建一个登录页面。当我运行代码时,我会收到这个异常;java.lang.IollegalStateException:提交响应后无法创建会话

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);
}

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

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);
}

最新更新