Mysql 的中文乱码问题解决总结
前几天自己做了一个小的系统,在系统中用到了mysql数据库,开发语言java。在系统中遇到了中文乱码问题。很让人头疼。记得去年做东西的时候也遇到这样的问题,想了很多的方法来解决。什么写转化类了,用java.net.url.encoding类里的编码解码了,文件过滤器了,设数据库的编码了。什么方法都用到了,最终问题解决了。所以这次以为不会有什么困难,结果确不像我想象的那样,下面我就说说其中的原因吧。
以前我们处理乱码会根据不同的情况做出不同的处理,一般没有什么问题,但现在确不行了,原因不是我们的方法思路有问题而是数据库的厂家有问题。现在mysql的主人变成了美国公司。mysql把它的默认编码变成了latinl字符集了。所以我们很难察觉到这一点。不管我们怎么处理都改变不了从数据库取出来后乱码,即使从前台传到服务器不乱码取出来存进去都会乱码。在建数据库和表的时候我们都选择utf8的。现在让我们看看自己的数据库的各个部分的编码:
进入命令行;SHOW VARIABLES LIKE 'character_set_%';
这是我改后的数据库编码,没改的里面有部分是latin的字符编码。如果没有改变的话它会是latinl的而不是utf8的。怎么改呢?
首先把你的jsp页面编码改成uft-8的。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
然后加上文件过滤器:
package com.skcc.dbm.admin;
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 {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null) {
// System.out.println(encoding);
request.setCharacterEncoding(encoding);
}
// System.out.println("Null");
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
在web.xml中的配置:
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>
com.roomadmin.admin.SetCharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>配置好以后别的什么处理乱码的工作都不用做了,个人认为是万能的。
当然,我们关键的措施还没有做呢,现在让我们来从根本上改变数据库的编码吧。
打开mysql的安装目录,我的在:D:/Program Files/MySQL/MySQL Server 5.0
打开:my.ini文件修改里面的默认编码:default-character-set=latinl 为default-character-set=utf8,一共有两处。现在重启mysql,ok,一切搞定。再来查看我们的数据库编码吧:
现在一切搞定。再不会有中文乱码了。