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

来源:互联网 发布:新浪nba数据库统计 编辑:程序博客网 时间:2024/04/29 17:57
Servlet 中文乱码问题及解决方案剖析
乱码分为,请求乱码和响应乱码  其中请求乱码有分为get乱码和post乱码 
1.响应乱码 
比如: 
OutputStream out = response.getOutputStream(); 
out.write(String ); 
输出中文时可能会出现乱码; 
 
Java代码:  
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");
原创粉丝点击