[Java][Servlet] Cannot call sendRedirect() after the response has been committed
做一个Login Demo的时候,写了如下代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request, response);
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if (userName.equals("test")) {
response.sendRedirect(request.getContextPath() + "/success/success.jsp");
} else {
response.sendRedirect(request.getContextPath() + "/error/login-failed.jsp");
}
}
运行程序时报错了Cannot call sendRedirect() after the response has been committed
,意思已经很明确了,就是说不能在一个response做了提交之后再重定向,也就是说再重定向之前不要去改变response,包括如下部分:
- 修改response中参数的值,cookie,session 等
- 重定向
请注意在做doPost(..)的时候我这里调用了super.doPost(..),而super.doPost(..)做了什么呢?
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
response被修改了,我们注释掉super.doPost(..),程序正常运行。