这个问题在这里已经有答案了:
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);
}
1条答案
按热度按时间cigdeys31#
您的错误是因为在设置会话属性之前正在重定向:
无论何时将用户重定向或转发到其他页面,都需要确保在转发或重定向之前执行了任何操作。所以就这样改变它:
下面是清理过的代码,以及不需要的内容(在这里使用preparedstatement,因为手动构建语句并不安全,正如前面提到的注解一样)