Chinaunix首页 | 论坛 | 博客
  • 博客访问: 410919
  • 博文数量: 155
  • 博客积分: 2590
  • 博客等级: 少校
  • 技术积分: 2161
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-25 09:33
文章分类

全部博文(155)

文章存档

2015年(1)

2014年(2)

2013年(55)

2012年(97)

分类: 系统运维

2012-12-22 16:57:52

乱码分为,请求乱码和响应乱码  其中请求乱码有分为get乱码和post乱码 
1.响应乱码 
比如: 
OutputStream out = response.getOutputStream(); 
out.write(String ); 
输出中文时可能会出现乱码; 
 
Java代码:  
  1. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {      
  2.         OutputStream out = response.getOutputStream();  
  3.         String data = "博客";  
  4.         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进行解码; 
等价于 
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");
原文:
阅读(678) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~