Servlet 输出中文乱码问题



Servlet 输出中文乱码问题.

今天在做项目时,又发现了乱码问题,我在servlet 传值到javascript去,js上面显示的总是乱码.刚开始我总是以为是JS报的乱码.最后终于让我发现了.原来问题是在servlet.请看代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter liuzm = response.getWriter();
response.setCharacterEncoding(“utf-8″);
response.setContentType(“text/html; charset=utf-8″);
liuzm.print(“刘志猛”);
}
输出总是乱码,看到心就烦,看正确代码:
//情况1:正常,浏览器按utf-8方式查看
response.setContentType(“text/html; charset=gbk”);
response.setCharacterEncoding(“utf-8″);
//情况2:正常,浏览器按简体中文方式查看
//response.setContentType(“text/html; charset=utf-8″);
//response.setCharacterEncoding(“gbk”);
PrintWriter liuzm= response.getWriter();
liuzm.print(“中文”);
不知道大家看到没有 PrintWriter liuzm= response.getWriter();
在response.setContentType(“text/html; charset=gbk”); 后面
其实问题就在这
结论:
1.在servlet中输出中文,如果采用PrintWriter方式,需要在调用getPrintWriter()之前调用setContentType 或者 setCharacterEncoding;

http://blog.sina.com.cn/s/blog_6742ac230100l2h2.html