Cannot call sendRedirect() after the response has been committed解决方法
<% JudgeName judge = new JudgeName(); request.setCharacterEncoding("utf-8"); String name = request.getParameter("userName"); if (name != null) { session.setAttribute("name", name); session.setMaxInactiveInterval(30); } else { response.sendRedirect("index.jsp"); /* return; */ } String pwd = request.getParameter("pwd"); if (judge.isExists(name)) { if (pwd.equals("12345")) { response.sendRedirect("succeed.jsp"); /*return;*/ } else { session.setAttribute("msg", "密码错误"); response.sendRedirect("failed.jsp"); /*return;*/ } } else { session.setAttribute("msg", "用户名不存在"); response.sendRedirect("failed.jsp");
/*return;*/ } %>
该页面主要实现的功能是对request的数据进行对比判断,由form表单进入该页面并不会出错,但是由于逻辑混乱导致直接进入页面时会发生两次response的重定向,所以报错
逻辑上的错误导致response可能被执行两次,两种解决方案:
1.修改逻辑
2.在response后加return;
3.但是不能再最后一个response后添加return;否则报错:
以下为修改后的代码:
<% JudgeName judge = new JudgeName(); request.setCharacterEncoding("utf-8"); String name = request.getParameter("userName"); String pwd = request.getParameter("pwd"); if (name != null && pwd != null) { session.setAttribute("name", name); session.setMaxInactiveInterval(30); if (judge.isExists(name)) { if (pwd.equals("12345")) { response.sendRedirect("succeed.jsp"); } else { session.setAttribute("msg", "密码错误"); response.sendRedirect("failed.jsp"); } } else { session.setAttribute("msg", "用户名不存在"); response.sendRedirect("failed.jsp"); } } else { response.sendRedirect("index.jsp"); } %>