Cannot call sendError() after the response has been committed - baiyangliu
当response提交后,不能调用sendError(),什么意思?
出现这个错误,一定是多次response导致的。可以这么理解,承载客户端和服务器进行Http交互的Socket连接已经关闭了,而你还试图发送数据给客户端,显然会出错。就好比我俩打电话,我都挂电话了,你还在“喂喂喂”。
例如下面这段代码就会出现此错误:
- import java.io.Writer;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- public class LoginAction extends ActionSupport {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private String userName;
- private String pwd;
- private String verifyCode;
- private String ajax;
- // 错误的写法
- @Override
- public String execute() throws Exception {
- // 通过ajax登录
- if (ajax != null) {
- HttpServletResponse response = ServletActionContext.getResponse();
- Writer writer = response.getWriter();
- writer.write("登录成功!");
- writer.flush();
- writer.close();
- }
- return SUCCESS;
- }
- // 正确写法
- public String login1() throws Exception {
- if (ajax != null) {
- HttpServletResponse response = ServletActionContext.getResponse();
- Writer writer = response.getWriter();
- writer.write("登录成功!");
- writer.flush();
- writer.close();
- return null;
- }
- return SUCCESS;
- }
- // 正确写法
- public String login2() throws Exception {
- if (ajax != null) {
- HttpServletResponse response = ServletActionContext.getResponse();
- Writer writer = response.getWriter();
- writer.write("登录成功!");
- writer.flush();
- writer.close();
- }
- return null;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPwd() {
- return pwd;
- }
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
- public String getVerifyCode() {
- return verifyCode;
- }
- public void setVerifyCode(String verifyCode) {
- this.verifyCode = verifyCode;
- }
- public String getAjax() {
- return ajax;
- }
- public void setAjax(String ajax) {
- this.ajax = ajax;
- }
- }
以上为登录测试代码(Struts2),在以上示例中,如果判断为ajax!=null成立,那么一定会报如题所示的错误,原因就是:if子句里已经做了一次response,在writer.close();的时候,本次response已经完成;但是紧接着在return SUCCESS;的时候,相当于又做了一次response,所以就出错了~
类似的错误也会出现于以下代码中:
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- Writer writer = response.getWriter();
- writer.write("Hello");
- writer.flush();
- writer.close();
- response.sendRedirect("http://blog.csdn.net/baiyanglu/article/details/8076104");
- }
出现本错误后,web前端能够接收到第一次response的内容(就是说,挂电话之前说的话,我还是可以听到的,挂电话后讲的,当然听不到咯~),不会报错,只会在后台显示出错了
以上,转自http://www.cnblogs.com/wang3680/p/2c5f28ecfb8c2e2772474f3fab4d771c.html
posted on 2017-03-08 20:52 struggle_beiJing 阅读(690) 评论(0) 编辑 收藏 举报