查看setCharacterEncoding API文档,进一步发现:
Calling setContentType(java.lang.String) with the String of text/html and calling this method with the String of UTF-8 is equivalent with calling setContentType with the String of text/html; charset=UTF-8.
原来只需要用response.setContentType("text/html; charset=utf-8"); 设定就ok,不需要两次调用。进一步
This method can be called repeatedly to change the character encoding. ......If the character encoding has already been set by setContentType(java.lang.String) or setLocale(java.util.Locale), this method overrides it.
可反复设置,相互覆盖,据此写出如下测试代码
java 代码
 
  1. //情况1:正常,浏览器按utf-8方式查看   
  2. response.setContentType("text/html; charset=gbk");   
  3. response.setCharacterEncoding("utf-8");   
  4. //情况2:正常,浏览器按简体中文方式查看   
  5. //response.setContentType("text/html; charset=utf-8");   
  6. //response.setCharacterEncoding("gbk");   
  7.   
  8. PrintWriter pw = response.getWriter();   
  9. pw.print("中文");  
结论:
1.在servlet中输出中文,如果采用PrintWriter方式,需要在调用getPrintWriter()之前调用setContentType 或者 setCharacterEncoding;采用ServletOutputStream方式,不受此限。
2.setContentType 和 setCharacterEncoding两方法中设定characterEncoding的方法对服务器效果一致,不需要反复调用。在输出文本内容时,采用response.setContentType("text/html; charset=utf-8");似乎更为方便。