排查原因:打断点,查看到底是在执行存数据库操作之前就已经乱码了,还是存数据库操作后乱码的。
1、前者解决方案:
在web.xml里面加上:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param:>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在配置jdbc数据源的时候加上:
jdbc:mysql://127.0.0.1:3306/logistics?useUnicode=true&characterEncoding=UTF-8
2、若为后者存数据库操作后乱码,解决方案:
登录数据库,执行如下sql:
show variables like 'character%';
结果:
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
说明在安装数据库的时候,character_set_database,character_set_server编码格式设置错误。
解决:
找到mysql安装路径下的my.cnf文件在[mysqld]下添加如下两行:
character_set_server=utf8
init_connect='SET NAMES utf8'
再次查看(注意:修改过后mysql的服务一定要重启才会生效),问题解决:
| 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