今天做struts2+hibernate+spring+mysql整合向数据库保存中文时出现乱码问题,在网上查资料好半天才解决。
首先查资料说是在struts.properties加入如下的key-value:struts.locale=zh_CN ;struts.i18n.encoding=gb2312-------向数据库保存数据时出现乱码,问题没有解决;
然后再查说是将spring的配置文件<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"></property>写成这样---------再试验保存数据还是乱码,问题没有解决;
然后再查说将mysql字符集设置为UTF-8----------再试验保存数据还是乱码,问题没有解决;
然后再查说写个filter
1 public class NewFilterDispatcher extends FilterDispatcher {
2 private static String encoding = "GBK";
3
4 public void init(FilterConfig filterConfig) throws ServletException {
5 super.init(filterConfig);
6 String encodingParam = filterConfig.getInitParameter("encoding");
7 if (encodingParam != null && encodingParam.trim().length() != 0) {
8 encoding = encodingParam;
9 }
10 }
11
12 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
13 throws IOException, ServletException {
14 request.setCharacterEncoding(encoding);
15 super.doFilter(request, response, chain);
16 }
17 }
web.xml
<filter>
<filter-name>struts</filter-name>
<filter-class>util.NewFilterDispatcher</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
再试验保存数据,这次乱码问题终于解决;