Servlet 中文乱码问题及解决方案剖析

原文地址: http://blog.csdn.net/xiazdong/article/details/7217022

乱码分为,请求乱码和响应乱码  其中请求乱码有分为get乱码和post乱码

1.响应乱码
比如:
OutputStream out = response.getOutputStream();
out.write(String );
输出中文时可能会出现乱码;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		OutputStream out = response.getOutputStream();
		String data = "博客";
		out.write(data.getBytes("UTF-8"));
	}


输出乱码的问题是程序用UTF-8编码,而浏览器用GB2312解码,因此会出现乱码;
解决:
添加
response.setCharacterEncoding("UTF-8");
目的是用于response.getWriter()输出的字符流的乱码问题,如果是response.getOutputStream()是不需要此种解决方案的;因为这句话的意思是为了将response对象中的数据以UTF-8解码后发向浏览器;
respnse.setHeader("content-type","text/html;charset=UTF-8");
目的是为了控制浏览器的行为,即控制浏览器用UTF-8进行解码;
等价于<meta http-equiv="content-type" content="text/html"/>

2.请求乱码
get乱码:
new String(request.getParameter("pointName").getBytes("ISO-8859-1"),"UTF-8");
get乱码还可以更改tomcat编码方式来解决  设置server.xml中connection节点中的URIEncoding="UTF-8"
post乱码:
request.setCharacterEncoding("UTF-8");

猜你喜欢

转载自jie66989.iteye.com/blog/1752356