问题描述
private void login(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, ServletException {// TODO Auto-generated method stubString username=req.getParameter("username");String password=req.getParameter("password");String captcha=req.getParameter("captcha");String captcha1=(String)req.getSession().getAttribute("captcha");if(!captcha.equals(captcha1)){req.setAttribute("error","验证码错误");req.getRequestDispatcher("/security/login.jsp").forward(req, resp);}User user=userDao.login(username,password);if(user!=null){user.setLast_login(new Date());userDao.update(user);req.getSession().setAttribute("user", user);req.getRequestDispatcher("index.jsp").forward(req, resp);}else{req.setAttribute("error", "用户名或密码错误");req.getRequestDispatcher("/security/login.jsp").forward(req,resp);}}第一次登录 输入错误的用户名密码 能成功跳转回去 提示错误。登录成功之后,再一次返回login.jsp界面 输入一个错误的用户名密码 这时报错:java.lang.IllegalStateException: Cannot forward after response has been committed但是输入正确的用户名密码却一切正常。起初我以为是成功后跳转使用了response 但是我改成了request之后也一样出错?
解决方案
引用private void login(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, ServletException {// TODO Auto-generated method stubString username=req.getParameter("username");String password=req.getParameter("password");String captcha=req.getParameter("captcha");String captcha1=(String)req.getSession().getAttribute("captcha");if(!captcha.equals(captcha1)){req.setAttribute("error","验证码错误");req.getRequestDispatcher("/security/login.jsp").forward(req, resp);//////////////////////////////return; //登入出错就返回,不能让其继续运行///////////////////////////////}User user=userDao.login(username,password);if(user!=null){user.setLast_login(new Date());userDao.update(user);req.getSession().setAttribute("user", user);req.getRequestDispatcher("index.jsp").forward(req, resp);}else{req.setAttribute("error", "用户名或密码错误");req.getRequestDispatcher("/security/login.jsp").forward(req,resp);}}
解决方案二:
成功后跳转使用了response 就会出这个错! 怪异! 我也很期待看下你这个到底啥问题哈!