根本原因是对于同一个response,不能同时创建
PrintWriter writer = resp.getWriter(); 与
ServletOutputStream outputStream = resp.getOutputStream();
源码中可以看到原因
public ServletOutputStream getOutputStream() throws IOException {
if (this.usingWriter) { //对于同一个response不允许同时存在
throw new IllegalStateException(sm.getString("coyoteResponse.getOutputStream.ise"));
} else {
this.usingOutputStream = true; //看这里
if (this.outputStream == null) {
this.outputStream = new CoyoteOutputStream(this.outputBuffer);
}
return this.outputStream;
}
}
public PrintWriter getWriter() throws IOException {
if (this.usingOutputStream) {
throw new IllegalStateException(sm.getString("coyoteResponse.getWriter.ise"));
} else {
if (ENFORCE_ENCODING_IN_GET_WRITER) {
this.setCharacterEncoding(this.getCharacterEncoding());
}
this.usingWriter = true;
this.outputBuffer.checkConverter();
if (this.writer == null) {
this.writer = new CoyoteWriter(this.outputBuffer);
}
return this.writer;
}
}