- 概要
- 问题
- 解决
- MySQL的配置连接
- web.xml的配置
- MySQL数据库配置
- 参考
在配置Spring + Hibernate存入MySQL数据库时有中文乱码的问题,尝试了解决办法。
问题中文乱码解决起来有时会找不到头绪,必须要把各个配置都做正确才能解决,以下是几个注意点。
解决 MySQL的配置连接在dispatcherServlet-servlet.xml里的设置尝试了多种配置,如下:
web.xml的配置com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/myNews?useUnicode=true&characterEncoding=utf-8 root P@ssw0rd
设置SetCharacterEncodingFilter方法
setEncodingFilter com.SetCharacterEncodingFilter encoding utf-8
SetCharacterEncodingFilter 实现 Filter
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)
request.setCharacterEncoding(encoding);
}
// 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);
}
MySQL数据库配置
my.ini里配置
character_set_server=utf8
并重启MySQL
MySQL数据库的整体Collation设置为utf8_bin
MySQL数据库的各中文字段设置Type为varchar,Collation设置为utf8_bin
MysqlDataTruncation: Data truncation: Incorrect string value: ‘xF0x9Dx90xB6"#…’ for column
100% solution java.sql.SQLException : Unsupported character encoding ‘utf8mb4’.
史上最全的Spring MVC 中文乱码问题解决方案



