我正在尝试使用MySQL为Java Web应用程序创建登录页面。当我运行代码时,我收到此异常。 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);
}
答案 0 :(得分:0)
您的错误是因为您在设置会话属性之前正在重定向:
HttpSession session=request.getSession();
session.setAttribute("name",uid); }
response.sendRedirect("http://localhost:8080/FinalYearProjec/userprofile.jsp"); //put this last
每当您将用户重定向或转发到其他页面时,都需要确保在转发或重定向之前执行了要执行的任何操作。因此,只需像这样更改它:
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);
}
这是您的代码,并且不需要的东西也被清除了(在这里使用preparestatement,因为手动构建您的语句并不安全,因为已经提到了注释。)
SELECT CONCAT('A purchase with the purchase ID of' AS "Constraint",
ONLINEPURCHASE.PurchaseID AS "OLID", 'is an online purchase of type' AS "Condition", ONLINEPURCHASE.OnlineType AS "OLType", 'and also a walkin purchase of location' AS "Condition", WALKINPURCHASE.ShopLocation AS "ShopLocation")
FROM ONLINEPURCHASE JOIN WALKINPURCHASE
ON ONLINEPURCHASE.PurchaseID = WALKINPURCHASE.PurchaseID
WHERE WALKINPURCHASE.PurchaseID IN (SELECT PurchaseID
FROM WALKINPURCHASE);