Servlet是否需要手动关闭输出流?

参考:Servlet不用手动关闭输出流么?-CSDN社区

测试用的是tomcat7.0,resoponse如果没有关闭,tomcat会自动关闭 org.apache.catalina.core.ApplicationDispatcher.doForward(ServletRequest request, ServletResponse response)方法 最后一段代码是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Close anyway
try {
PrintWriter writer = response.getWriter();
writer.close();
} catch (IllegalStateException e) {
try {
ServletOutputStream stream = response.getOutputStream();
stream.close();
} catch (IllegalStateException f) {
// Ignore
} catch (IOException f) {
// Ignore
}
} catch (IOException e) {
// Ignore
}

可以清楚看到不管你有没有关闭,tomcat都重新关闭了一次