---
title: "如何彻底解决java开发中的乱码问题"
author: "kaka99"
date: "2008-10-23T09:02:08Z"
tags: ["Gmail", "JSP", "Java", "Web", "XML"]
slug: "java"
draft: false
lastmod: "2008-10-23T09:02:08Z"
id: 256712
url: "https://kaka99.iteye.com/blog/256712"
---

在java开发中，经常会遇到乱码问题（包括中文乱码、其他国家语言文字乱码等），怎么样才能花最小的代价来解决这个问题呢？下面就将提供一种方式来彻底解决这个麻烦。（本方法已经在很多项目中使用，希望能给那些为乱码困扰的朋友带来帮助！）  
方法分成以下3个步骤（请放心，每一步都非常简单）  
1\. 首先将开发项目（如在Eclipse中创建的项目）的设置成UTF-8编码方式（如下图）。这一点在开始一个新的项目的时候尤其重要，目前的项目基本上都使用UTF-8编码了。

2\. 确保项目内的所有开发文件都是UTF-8编码的。这里的开发文件主要指：java，jsp，html，js，css，xml类型等开发涉及到的文件，当然 图片文件就不用了，貌似没有UTF-8的图形文件。其中的java，js，css，xml类型文件，只要文件的编码方式为UTF-8就可以了。而jsp文 件则还需要在文件内容中设置如下：  
Html代码

```
<%@ page contentType=“text/html;charset=UTF-8″%> 
… 
<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8″> 
… 
<%@ page contentType="text/html;charset=UTF-8"%>
...
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
```

   
...另外html文件还需要在文件内容中设置：

```
… 
<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8″> 
… 
...
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
```

 

...对jsp文件和html文件要特别注意，大多数时候遇到乱码是因为粗心没有进行UTF-8编码或者文件内容没有设置对造成的。遇到乱码问题一般先检查相应的文件编码和内容是否符合要求。  
如果原来不是UTF-8编码的可以用文本工具进行转换，包括最简单的记事本也可以将打开的文件另存为UTF-8编码，当然可以用UltraEdit工具转换\[菜单：文件-转换-ASCII转UTF-8]更加方便。  
3\. 在项目应用中加一个编码虑镜。编码虑镜的代码（很简单的）具体如下：  
Java代码

```
/* 
* Created on 2005-11-6 
* Author stephen 
* Email zhoujianqiang AT gmail DOT com 
* CopyRight(C)2005-2008 , All rights reserved. 
*/ 
package com.soft4j.filter; 

import java.io.IOException; 
import javax.servlet.*; 

public class CharsetFilter implements Filter { 

protected String encoding = null;// ///要制定的编码，在web.xml中配置 

protected FilterConfig filterConfig = null; 

public void destroy() { 

this.encoding = null; 
this.filterConfig = null; 

} 

public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain) throws IOException, ServletException { 

if (request.getCharacterEncoding() == null) { 
String encoding = getEncoding();// //得到指定的编码名字 
if (encoding != null) 
request.setCharacterEncoding(encoding);// //设置request的编码 
} 

chain.doFilter(request, response);// /有机会执行下一个filter 

} 

public void init(FilterConfig filterConfig) throws ServletException { 

this.filterConfig = filterConfig; 
this.encoding = filterConfig.getInitParameter(“encoding”);// /得到在web.xml中配置的编码 
} 

protected String getEncoding() { 

return (this.encoding);// /得到指定的编码 

} 

} 
/*
 * Created on 2005-11-6
 * Author stephen
 * Email zhoujianqiang AT gmail DOT com
 * CopyRight(C)2005-2008 , All rights reserved.
 */
package com.soft4j.filter;

import java.io.IOException;
import javax.servlet.*;

public class CharsetFilter implements Filter {

    protected String encoding = null;// ///要制定的编码，在web.xml中配置

    protected FilterConfig filterConfig = null;

    public void destroy() {

        this.encoding = null;
        this.filterConfig = null;

    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        if (request.getCharacterEncoding() == null) {
            String encoding = getEncoding();// //得到指定的编码名字
            if (encoding != null)
                request.setCharacterEncoding(encoding);// //设置request的编码
        }

        chain.doFilter(request, response);// /有机会执行下一个filter

    }

    public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");// /得到在web.xml中配置的编码
    }

    protected String getEncoding() {

        return (this.encoding);// /得到指定的编码

    }

}
```

 

编码虑镜的使用方法：只要在项目的web.xml文件的开头中加入如下的配置参数就可以了：  
Xml代码

```
<filter> 
<filter-name>SetCharacterEncoding</filter-name> 
<filter-class>com.soft4j.filter.CharsetFilter</filter-class> 
<init-param> 
<param-name>encoding</param-name> 
<param-value>UTF-8</param-value> 
</init-param> 
</filter> 
<filter-mapping> 
<filter-name>SetCharacterEncoding</filter-name> 
<url-pattern>/*</url-pattern> 
</filter-mapping> 
 <filter>
  <filter-name>SetCharacterEncoding</filter-name>
  <filter-class>com.soft4j.filter.CharsetFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>SetCharacterEncoding</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
```

 

这样能确保所有出入项目的调用都是UTF-8编码的。  
经过上面的3个步骤后，你的java项目就不必再受到乱码的困扰了，当然在实际的开发中，由于使用一些第3方的开源组件可能会遇到乱码问题，不 过，大部分的问题都是由于开源组件造成的，不必怀疑自己的项目。只要对开源组件中的编码方式进行设置或者作相应的修改，一般就能解决问题。

 

 

 

本文来源于 冰山上的播客 [http://xinsync.xju.edu.cn](http://xinsync.xju.edu.cn) , 原文地址：[http://xinsync.xju.edu.cn/index.php/archives/2952](http://xinsync.xju.edu.cn/index.php/archives/2952)