在进行web开发时经常会遇到中文显示乱码的问题,这是由于Java内置的字符集与页面以及数据库内部的字符集不一致所导致,为了解决这个问题,可以定义一个Filter,然后在web.xml中配置相应的参数即可,下面结合自己的实践来给出一种解决方案。
1 数据库编码配置,以Mysql为例
默认安装的mysql的字符集是不支持中文的,我们可以修改相关的配置使之支持,操作如下:
在mysql的安装目录下找到配置文件my.ini,我的在C:\Program Files\MySQL\MySQL Server 5.1目录下,
修改default-character-set=gb2312 ,当然也可以是utf-8,gbk等,但需要注意编码一定要一致,即网页的编码和数据库以及Java内置的编码要一致。
保存就可,然后重新启动mysql服务,打开cmd终端,命令如下:
net stop mysql //停止mysql服务
net start mysql //启动mysql服务
2 修改网页中的编码方式:
<%@page contentType="text/html" pageEncoding="GB2312"%>
3 修改Java内置编码,jsp为例
<%@page language="java" contentType="text/html; charset=GB2312"%>
4 修改hibernate的配置文件:hibernate.cfg.xml
<property name="connection.url">
<![CDATA[
jdbc:mysql://localhost:3306/database-name?useUnicode=true&characterEncoding=gb2312]]>
</property>
一般上述即可解决问题,如果还没有解决,可以定义一个Filter,配置web.xml使之自动转化为配置的编码方式
5 定义一个设置编码Filter类,这个类要实现Filter接口,然后在web.xml
SetEncodingFilter类实现了Filter接口
package com.stuman.web.filters;
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 SetEncodingFilter 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 {
if (ignore || (request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(selectEncoding(request));
}
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")
|| value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
public FilterConfig getFilterConfig() {
return filterConfig;
}
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
}
配置web.xml
在web.xml中加入如下配置属性:
<filter>
<filter-name>SetCharsetEncodingFilter</filter-name>
<filter-class>com.stuman.util.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
我配置的的编码方式是gb2312,当然也可以是别的编码方式,只要保持一致就可