一、常识了解
1.GBK包含GB2312,即如果通过GB2312编码后可以通过GBK解码,反之可能不成立; 2.java.nio.charset.Charset.defaultCharset() 获得平台默认字符编码; 3.getBytes() 是通过平台默认字符集进行编码;二、中文乱码出现
在学习任何一门技术时,经常会有初学者遇到中文乱码问题,比如MySQL,是因为在安装时没有设置;而在Servlet中,也会遇到中文乱码问题; 比如: 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"));
- }
三、response中文乱码
在网上很有效的解决方法是添加: response.setCharacterEncoding("UTF-8"); 解决不了,后来又搜到一条解决方法是: respnse.setHeader("content-type","text/html;charset=UTF-8"); 两句都填上,后来终于解决了这个问题; 其实我们应该思考一下本质;问题1:
我们这里先来说明一下错误的原因,下图是显示乱码的流程图:

问题2
问题代码如下:
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- PrintWriter out = response.getWriter();
- String data = "博客";
- out.println(data);
- }
错误代码流程图:

解决方案流程图:

补充:通过<meta>标签模拟response头;
<meta http-equiv="content-type" content="text/html"/> 等价于 response.setContentType("text/html");四、request乱码问题
request请求分为post和get,对于不同的请求方式有不同的解决乱码的方案;1.post请求乱码
错误原因:

2.get请求乱码

爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情