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


一、常识了解

 

1.GBK包含GB2312,即如果通过GB2312编码后可以通过GBK解码,反之可能不成立;

2.java.nio.charset.Charset.defaultCharset() 获得平台默认字符编码;

3.getBytes() 是通过平台默认字符集进行编码;

 

二、中文乱码出现

 

在学习任何一门技术时,经常会有初学者遇到中文乱码问题,比如MySQL,是因为在安装时没有设置;而在Servlet中,也会遇到中文乱码问题;

比如:

OutputStream out = response.getOutputStream();

out.write(String );

输出中文时可能会出现乱码;

比如:

[java]
  1. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  2.           
  3.         OutputStream out = response.getOutputStream();  
  4.         String data = "博客";  
  5.         out.write(data.getBytes("UTF-8"));  
  6.     }  

输出乱码的问题是程序用UTF-8编码,而浏览器用GB2312解码,因此会出现乱码;

 

三、解决中文乱码

 

在网上很有效的解决方法是添加:

response.setCharacterEncoding("UTF-8");

解决不了,后来又搜到一条解决方法是:

respnse.setHeader("content-type","text/html;charset=UTF-8");

两句都填上,后来终于解决了这个问题;

其实我们应该思考一下本质;

  • 1
  • 2
  • 下一页

相关内容