Java乱码问题解决方案
Java乱码问题一直是困扰初学者的一个难题,下面就根据笔者的经验来给大家一个解决方案。我写了一个Demo的web应用,解决了乱码问题, 点击下载。1 问题来源
Java的乱码问题,根源在于操作系统、数据库(MySQL)、Web服务器(Tomcat)、页面(JSP)中的编码不一致造成的。例如,mysql的编码是latin1,而页面上字符的编码是GBK,则就会出现乱码问题。
2 解决方案
了解了乱码产生的原因,下面就来看一下如何解决乱码。事实上,只要保证各个环节的编码一致,就不会产生乱码, 所以只要将所有的环节,设置的编码为UTF-8,就不会出现乱码了(为了支持国际化,建议统一设置成UTF-8)。
3 mysql数据库编码的设置(以MySQL 5.0.41为例)
- 查看数据库支持的编码:show character set;
这样可以查看mysql数据库支持的所有编码,其中可以看到有支持utf8编码。
mysql
>
show
character
set
;
+ -- --------+-----------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+ -- --------+-----------------------------+---------------------+--------+
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| koi8r | KOI8 - R Relcom Russian | koi8r_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_ci | 1 |
| latin2 | ISO 8859 - 2 Central European | latin2_general_ci | 1 |
| swe7 | 7 bit Swedish | swe7_swedish_ci | 1 |
| ascii | US ASCII | ascii_general_ci | 1 |
| ujis | EUC - JP Japanese | ujis_japanese_ci | 3 |
| sjis | Shift - JIS Japanese | sjis_japanese_ci | 2 |
| hebrew | ISO 8859 - 8 Hebrew | hebrew_general_ci | 1 |
| tis620 | TIS620 Thai | tis620_thai_ci | 1 |
| euckr | EUC - KR Korean | euckr_korean_ci | 2 |
| koi8u | KOI8 - U Ukrainian | koi8u_general_ci | 1 |
| gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2 |
| greek | ISO 8859 - 7 Greek | greek_general_ci | 1 |
| cp1250 | Windows Central European | cp1250_general_ci | 1 |
| gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |
| latin5 | ISO 8859 - 9 Turkish | latin5_turkish_ci | 1 |
| armscii8 | ARMSCII - 8 Armenian | armscii8_general_ci | 1 |
| utf8 | UTF - 8 Unicode | utf8_general_ci | 3 |
| ucs2 | UCS - 2 Unicode | ucs2_general_ci | 2 |
| cp866 | DOS Russian | cp866_general_ci | 1 |
| keybcs2 | DOS Kamenicky Czech - Slovak | keybcs2_general_ci | 1 |
| macce | Mac Central European | macce_general_ci | 1 |
| macroman | Mac West European | macroman_general_ci | 1 |
| cp852 | DOS Central European | cp852_general_ci | 1 |
| latin7 | ISO 8859 - 13 Baltic | latin7_general_ci | 1 |
| cp1251 | Windows Cyrillic | cp1251_general_ci | 1 |
| cp1256 | Windows Arabic | cp1256_general_ci | 1 |
| cp1257 | Windows Baltic | cp1257_general_ci | 1 |
| binary | Binary pseudo charset | binary | 1 |
| geostd8 | GEOSTD8 Georgian | geostd8_general_ci | 1 |
| cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2 |
| eucjpms | UJIS for Windows Japanese | eucjpms_japanese_ci | 3 |
+ -- --------+-----------------------------+---------------------+--------+
36 rows in set ( 0.00 sec
+ -- --------+-----------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+ -- --------+-----------------------------+---------------------+--------+
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| koi8r | KOI8 - R Relcom Russian | koi8r_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_ci | 1 |
| latin2 | ISO 8859 - 2 Central European | latin2_general_ci | 1 |
| swe7 | 7 bit Swedish | swe7_swedish_ci | 1 |
| ascii | US ASCII | ascii_general_ci | 1 |
| ujis | EUC - JP Japanese | ujis_japanese_ci | 3 |
| sjis | Shift - JIS Japanese | sjis_japanese_ci | 2 |
| hebrew | ISO 8859 - 8 Hebrew | hebrew_general_ci | 1 |
| tis620 | TIS620 Thai | tis620_thai_ci | 1 |
| euckr | EUC - KR Korean | euckr_korean_ci | 2 |
| koi8u | KOI8 - U Ukrainian | koi8u_general_ci | 1 |
| gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2 |
| greek | ISO 8859 - 7 Greek | greek_general_ci | 1 |
| cp1250 | Windows Central European | cp1250_general_ci | 1 |
| gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |
| latin5 | ISO 8859 - 9 Turkish | latin5_turkish_ci | 1 |
| armscii8 | ARMSCII - 8 Armenian | armscii8_general_ci | 1 |
| utf8 | UTF - 8 Unicode | utf8_general_ci | 3 |
| ucs2 | UCS - 2 Unicode | ucs2_general_ci | 2 |
| cp866 | DOS Russian | cp866_general_ci | 1 |
| keybcs2 | DOS Kamenicky Czech - Slovak | keybcs2_general_ci | 1 |
| macce | Mac Central European | macce_general_ci | 1 |
| macroman | Mac West European | macroman_general_ci | 1 |
| cp852 | DOS Central European | cp852_general_ci | 1 |
| latin7 | ISO 8859 - 13 Baltic | latin7_general_ci | 1 |
| cp1251 | Windows Cyrillic | cp1251_general_ci | 1 |
| cp1256 | Windows Arabic | cp1256_general_ci | 1 |
| cp1257 | Windows Baltic | cp1257_general_ci | 1 |
| binary | Binary pseudo charset | binary | 1 |
| geostd8 | GEOSTD8 Georgian | geostd8_general_ci | 1 |
| cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2 |
| eucjpms | UJIS for Windows Japanese | eucjpms_japanese_ci | 3 |
+ -- --------+-----------------------------+---------------------+--------+
36 rows in set ( 0.00 sec
- 查看数据库默认的编码: show variables like '%character%'
mysql
>
show variables
like
'
%character%
'
;
+ -- ------------------------+---------------------------------------+
| Variable_name | Value |
+ -- ------------------------+---------------------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | E:\mysql - 5.0 . 41 - win32\share\charsets\ |
+ -- ------------------------+---------------------------------------+
8 rows in set ( 0.00 sec)
+ -- ------------------------+---------------------------------------+
| Variable_name | Value |
+ -- ------------------------+---------------------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | E:\mysql - 5.0 . 41 - win32\share\charsets\ |
+ -- ------------------------+---------------------------------------+
8 rows in set ( 0.00 sec)
可以看到, mysql 数据库中,此时有关字符串的设置的参数,其中“ character_set_server ”为创建数据库是默认的编码,现在需要将其修改为 utf8 。
- 修改数据库默认的编码:set character_set_server='utf8';
mysql
>
set
character_set_server
=
'
utf8
'
;
Query OK, 0 rows affected ( 0.00 sec)
Query OK, 0 rows affected ( 0.00 sec)
执行改命令后,可以看到数据库此时的默认编码改为utf8了
mysql
>
show variables
like
'
%character%
'
;
+ -- ------------------------+---------------------------------------+
| Variable_name | Value |
+ -- ------------------------+---------------------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | E:\mysql - 5.0 . 41 - win32\share\charsets\ |
+ -- ------------------------+---------------------------------------+
8 rows in set ( 0.00 sec)
+ -- ------------------------+---------------------------------------+
| Variable_name | Value |
+ -- ------------------------+---------------------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | E:\mysql - 5.0 . 41 - win32\share\charsets\ |
+ -- ------------------------+---------------------------------------+
8 rows in set ( 0.00 sec)
此时,创建数据库和表如果不指定字符集,则也会使用uft8的编码了。
- 查看schema和table编码:
show create database 数据库名;
show create table 表名;
例如存在这样一个数据库mydbdefault,mydbdefault中有一个表test
mysql
>
use
mydbdefault;
Database changed
mysql > show create database mydbdefault;
+ -- -----------+-----------------------------------------------------------------
-- -----+
| Database | Create Database
|
+ -- -----------+-----------------------------------------------------------------
-- -----+
| mydbdefault | CREATE DATABASE `mydbdefault` /* !40100 DEFAULT CHARACTER SET latin1 */ |
+ -- -----------+-----------------------------------------------------------------
-- -----+
1 row in set ( 0.00 sec)
Database changed
mysql > show create database mydbdefault;
+ -- -----------+-----------------------------------------------------------------
-- -----+
| Database | Create Database
|
+ -- -----------+-----------------------------------------------------------------
-- -----+
| mydbdefault | CREATE DATABASE `mydbdefault` /* !40100 DEFAULT CHARACTER SET latin1 */ |
+ -- -----------+-----------------------------------------------------------------
-- -----+
1 row in set ( 0.00 sec)
数据库mydbdefault的编码为latin1
mysql
>
show
create
table
test;
+ -- -----+-----------------------------------------------------------------------
-- -----------------+
| Table | Create Table
|
+ -- -----+-----------------------------------------------------------------------
-- -----------------+
| test | CREATE TABLE `test` (
`id` int ( 20 ) default NULL
) ENGINE = MyISAM DEFAULT CHARSET = latin1 |
+ -- -----+-----------------------------------------------------------------------
-- -----------------+
1 row in set ( 0.00 sec)
+ -- -----+-----------------------------------------------------------------------
-- -----------------+
| Table | Create Table
|
+ -- -----+-----------------------------------------------------------------------
-- -----------------+
| test | CREATE TABLE `test` (
`id` int ( 20 ) default NULL
) ENGINE = MyISAM DEFAULT CHARSET = latin1 |
+ -- -----+-----------------------------------------------------------------------
-- -----------------+
1 row in set ( 0.00 sec)
表的编码为latin1
- 修改schema和table编码:
alter database 数据库名 character set utf8;
alter table 表名 character set utf8;
既然查出数据库和表的编码都不是uft8,所以此时要将数据库和表的字符集改成utf8。
mysql
>
alter
database
mydbdefault
character
set
utf8;
Query OK, 1 row affected ( 0.00 sec)
mysql > show create database mydbdefault;
+ -- -----------+-----------------------------------------------------------------
-- ---+
| Database | Create Database
|
+ -- -----------+-----------------------------------------------------------------
-- ---+
| mydbdefault | CREATE DATABASE `mydbdefault` /* !40100 DEFAULT CHARACTER SET utf
8 */ |
+ -- -----------+-----------------------------------------------------------------
-- ---+
1 row in set ( 0.00 sec)
mysql > alter table test character set utf8;
Query OK, 0 rows affected ( 0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql > show create table test;
+ -- -----+-----------------------------------------------------------------------
-- ---------------+
| Table | Create Table
|
+ -- -----+-----------------------------------------------------------------------
-- ---------------+
| test | CREATE TABLE `test` (
`id` int ( 20 ) default NULL
) ENGINE = MyISAM DEFAULT CHARSET = utf8 |
+ -- -----+-----------------------------------------------------------------------
-- ---------------+
1 row in set ( 0.00 sec)
Query OK, 1 row affected ( 0.00 sec)
mysql > show create database mydbdefault;
+ -- -----------+-----------------------------------------------------------------
-- ---+
| Database | Create Database
|
+ -- -----------+-----------------------------------------------------------------
-- ---+
| mydbdefault | CREATE DATABASE `mydbdefault` /* !40100 DEFAULT CHARACTER SET utf
8 */ |
+ -- -----------+-----------------------------------------------------------------
-- ---+
1 row in set ( 0.00 sec)
mysql > alter table test character set utf8;
Query OK, 0 rows affected ( 0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql > show create table test;
+ -- -----+-----------------------------------------------------------------------
-- ---------------+
| Table | Create Table
|
+ -- -----+-----------------------------------------------------------------------
-- ---------------+
| test | CREATE TABLE `test` (
`id` int ( 20 ) default NULL
) ENGINE = MyISAM DEFAULT CHARSET = utf8 |
+ -- -----+-----------------------------------------------------------------------
-- ---------------+
1 row in set ( 0.00 sec)
- 在不知道默认的编码方式的情况下,创建数据库和表时,最好指定字符编码为utf8:
create database 数据库名 character set utf8;
create table 表名 (….) character set utf8;
有关mysql的字符集的命令,可以mysql的参考手册http://dev.mysql.com/doc/refman/5.1/zh/charset.html
在Tomcat的安装目录下,找到TOMCAT_HOME\conf\server.xml,然后找到以下代码,在其后加上URIEncoding="UTF-8"
<
Connector
port
="8080"
protocol
="HTTP/1.1"
connectionTimeout ="20000"
redirectPort ="8443" URIEncoding ="UTF-8" />
connectionTimeout ="20000"
redirectPort ="8443" URIEncoding ="UTF-8" />
5 web应用中编码处理
在web应用中,为了确保提交的字符串为uft-8的,可以编写一个过滤器filter,过滤器的在web.xml中的配置如下:
对应的SetCharacterEncodingFilter类代码如下:
<
filter
>
< filter - name > Set Character Encoding </ filter - name >
< filter - class >
com.fengmanfei.util.SetCharacterEncodingFilter
</ filter - class >
< init - param >
< param - name > encoding </ param - name >
< param - value > UTF - 8 </ param - value >
</ init - param >
</ filter >
< filter - mapping >
< filter - name > Set Character Encoding </ filter - name >
< url - pattern > /* </url-pattern>
</filter-mapping>
< filter - name > Set Character Encoding </ filter - name >
< filter - class >
com.fengmanfei.util.SetCharacterEncodingFilter
</ filter - class >
< init - param >
< param - name > encoding </ param - name >
< param - value > UTF - 8 </ param - value >
</ init - param >
</ filter >
< filter - mapping >
< filter - name > Set Character Encoding </ filter - name >
< url - pattern > /* </url-pattern>
</filter-mapping>
过滤器的代码如下所示:
package
com.fengmanfei.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SetCharacterEncodingFilter implements Filter {
private String encoding = " UTF-8 " ;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter( " encoding " );
if (s != null ) {
encoding = s;
}
}
public void destroy() {
}
}
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SetCharacterEncodingFilter implements Filter {
private String encoding = " UTF-8 " ;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter( " encoding " );
if (s != null ) {
encoding = s;
}
}
public void destroy() {
}
}
其中,关键的是通过过滤器,将request请求设置UTF-8编码
6 数据库连接URL
jdbc:mysql://localhost:3306/mydb?characterEncoding=UTF-8
7 页面中编码处理
在jsp页面上,同时也要设置页面编码方式
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
8 Eclipse中编码的设置
最后,在使用Eclipse时,要将工作区的编码也设置为UTF-8,选择“Window”|“Preference”|“General”|“Workspace”,将Text file encodeing 改为UTF-8,如图所示: