---
title: "中文乱码问题解决汇总"
author: "sandy136138"
date: "2009-06-05T12:47:28Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-06-05T12:47:28Z"
id: 402438
url: "https://mose.iteye.com/blog/402438"
---

**1. 开发环境乱码 -- eclipse或ant编译乱码**  
将java系统默认的字符集cp1253 改成GBK  修改控制面板--区域与语言

否则在用ant运行java程序的时候会出现编码的错误  
原因是  
    java 在运行时会调用系统的默认配置文件System.getProperties();  
    其中 有个file.encoding 的属性决定编码集，如果是英文版的操作系统则file.encoding=CP1253  
所以ant 运行中文程序会乱码

如果不想修改系统默认字符集的话，可以再ant java target中加入下面语句

    &lt;javac srcdir="${project.src}"  
               destdir="${project.output.build}"  
               debug="on" encoding="UTF-8"  
               deprecation="on"  
                 listfiles="on"  
               includeAntRuntime="no"&gt;  
            &lt;compilerarg value="-Xlint:all"/&gt;  
            &lt;classpath refid="project.classpath"/&gt;  
            &lt;classpath refid="tomcat.classpath"/&gt;  
        &lt;/javac&gt;

    &lt;java classpathref="project.classpath" classname="com.mose.ParserEnglish" fork="true" failonerror="true"&gt;  
        &lt;sysproperty key="file.encoding" value="UTF-8"/&gt;  
        &lt;arg value="-h"/&gt;  
    &lt;/java&gt;

**2. web开发乱码**

**2.1 解决响应中的乱码**

何为响应中的乱码？把页面中的“username”改成“用户名”你就知道了。

 

![](https://docs.google.com/shared/images/jsp-ch-02-02-01-response-01.png)

所谓响应中的乱码，就是显示页面上的乱码，因为页面数据是从服务器一端放入响应（response）中，然后发送给浏览器，如果响应中的数据无法被正常解析，就会出现乱码问题。

 

**解决方法**

在http的响应（response）中添加编码信息，使用如下方式：

```
<%@ page contentType="text/html; charset=gb2312"%>
 
```

这段要放在jsp页面的第一行，用来指定响应的类型和编码格式，contentType为text/html就是html内容，charset表示编码为gb2312。这样浏览器就可以从响应中获得编码格式了。

 

还需要在html中指定编码格式。

```
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 <title>title</title>
</head>


```

**2.1 POST乱码**  
因为发送请求的时候，使用的编码是iso-8859-1，意味着只有英文是有效字符

把form里加上method="POST"，让form提交的时候使用POST方式。

怎么解决呢？我们要jsp最前面加上一条java语句，设置请求的字符编码。

```
<%
 request.setCharacterEncoding("gb2312");
%>

```

### []()2.2. GET乱码

直接点击超链接，form的默认提交方式都是GET。

POST方式下的解决方式还算简单，因为POST方式下提交的数据都是以二进制的方式附加在**http请求的body部分**发送，只需要在后台指定编码格式就足矣解决。

GET方式下会将参数直接附加到url后面，这部分参数无法使用request.setCharacterEncoding()处理，结果就是get形式的所有中文都变成了乱码。

 

```
<%
 String username = request.getParameter("username");
 byte[] bytes = username.getBytes("iso-8859-1");
 String result = new String(bytes, "gb2312");
 out.print(result);
%>


3.使用spring解决乱码问题
利用spring自定义的CharacterEncodingFilter，使用方式如下。

在web.xml文件中添加
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

//过滤器的实现代码

protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
            request.setCharacterEncoding(this.encoding);
            if (this.forceEncoding && responseSetCharacterEncodingAvailable) {
                response.setCharacterEncoding(this.encoding);
            }
        }
        filterChain.doFilter(request, response);
    }
```

 

```



附：JSP中的编码设置
```

1\. pageEncoding:&lt;%@ page pageEncoding="UTF-8"%&gt;

    设置JSP编译成Servlet时使用的编码    

 

2\. contentType: &lt;%@ page contentType="text/html; charset=UTF-8"%&gt;

    对服务器响应进行重新编码，即jsp的输出流在浏览器中显示的编码 

 

3\. html页面charset:&lt;META http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;

    网页的编码信息 ，说明页面制作所使用的编码

 

4\. request.setCharacterEncoding()  -- 可用在servlet和jsp页面中

    作用是设置对客户端请求进行重新编码的编码，即post方式提交的数据进行编码。

 

5\. response.setCharacterEncoding() -- 可用在servlet和jsp页面中

   对服务器响应进行重新编码，即jsp的输出流在浏览器中显示的编码，与&lt;%@ page contentType="text/html;charset=UTF-8"%&gt;一样

 

6\. response.setContentType() -- 可用在servlet和jsp页面中

   对服务器响应进行重新编码，即jsp的输出流在浏览器中显示的编码，与&lt;%@ page contentType="text/html;charset=UTF-8"%&gt;一样 

 

7.response.setHeader("Content-Type","text/html;charset=UTF-8");   -- 可用在servlet和jsp页面中

   与&lt;META http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;一样