最近一个FLEX+J2EE+IBATIS+MYSQL的项目在linux上部署后,出现了乱码问题,阵痛之后,把解决经营与大家分享。
1、首先确认mysql的编码.
mysql -uroot -p登入mysql后,用命令show variables like 'character%'; 查看编码设置。
我这边统一utf-8编码,所以
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
修改mysql编码:
找到/etc/mysql/my.cnf文件,
在找到[mysqld] 添加
default-character-set=utf8 /** 默认字符集为utf8 **/
[client]
default-character-set=utf8
修改好后,重新启动mysql 即可
2、FLEX和JAVA编码设置,这指的不是工程的Text File Encoding。
Text File Encoding只会影响代码,而不是请求的字符串。
FLEX设置<?xml version="1.0" encoding="utf-8"?>
JAVA工程就更方便了,做个filter即可。
WEB.XML
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.youcity.website.back.commom.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>
CODE:
public class SetCharacterEncodingFilter implements Filter {
private FilterConfig filterConfig = null;
/**
* Take this filter out of service.
*/
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
arg0.setCharacterEncoding(filterConfig.getInitParameter("encoding"));
arg2.doFilter(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
this.filterConfig = arg0;
}
}
3、最容易忽略的一点
创建数据表的时候,别忘了字符集设置 CHARSET=UTF8
如:
CREATE TABLE `review` (
`Id` int(11) NOT NULL auto_increment,
`refType` int(3) NOT NULL default '0',
`refId` int(11) NOT NULL default '0',
`count` int(11) NOT NULL default '0',
`comment` varchar(500) default NULL,
`userId` int(11) NOT NULL default '0',
`userName` varchar(50) default NULL,
`createTime` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=100000000 DEFAULT CHARSET=UTF8;
4、TOMCAT设置,在 SERVER.XML中加入URIEncoding="UTF-8"
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
注意以上几处,你的工程将不会出现乱码问题。