向数据库插入中文乱码【转】

 

又遇到乱码问题,这个编码问题有时候真是让人头大。找了半天都找不出来哪里出了问题,页面和数据库均是使用utf8编码,但是还是出现了乱码。直接在命令行下向数据库插入中文数据时不会出现乱码,在程序中使用代码插入时会出现乱码,控制台中打印出来数据没有乱码,没搞清楚哪里出了问题。通过查找资料最终将乱码问题解决,但是还有些不明白问题出在哪里。

通过在数据库连接url中加入?useUnicode=true&characterEncoding=UTF-8解决问题:

applicationContext.xml

 

[html]  view plain copy print ?
 
  1. <bean id="dataSource"  
  2.     class="org.apache.commons.dbcp.BasicDataSource"  
  3.     destroy-method="close">  
  4.     <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  5.     <property name="url"  
  6.         value="jdbc:mysql://localhost:3306/cms?useUnicode=true&characterEncoding=UTF-8" />  
  7.     <property name="username" value="root" />  
  8.     <property name="password" value="" />  
  9.   
  10. </bean>  

我的处理编码的filter:

 

 

[java]  view plain copy print ?
 
  1. public class EncodingFilter implements Filter {  
  2.   
  3.     private FilterConfig config;  
  4.     private String charset = "UTF-8";  
  5.   
  6.     public void init(FilterConfig filterconfig) throws ServletException {  
  7.         config = filterconfig;  
  8.         String s = config.getInitParameter("encoding");  
  9.         if (s != null) {  
  10.             charset = s;  
  11.         }  
  12.     }  
  13.   
  14.     public void destroy() {  
  15.         config = null;  
  16.     }  
  17.   
  18.     public void doFilter(ServletRequest servletrequest,  
  19.             ServletResponse servletresponse, FilterChain filterchain)  
  20.             throws IOException, ServletException {  
  21.           
  22.         servletrequest.setCharacterEncoding(charset);  
  23.         servletresponse.setCharacterEncoding(charset);  
  24.           
  25.         filterchain.doFilter(servletrequest,servletresponse);  
  26.     }  
  27.   
  28. }  

 

经测试filter确实被执行了。

数据库是使用utf8编码:

jsp页面和所有Java文件都是使用的utf8编码。
没看出问题具体出现在哪一点,目前有点赶时间,先把问题解决了,有时间的好好研究一下这个编码问题。遇到很多次了,还不能小看这个编码问题。上次在程序中使用utf8编码的url地址访问windows服务器上的资源文件,出现404,改用gbk就能够访问了。还有一次发现页面在低版本chrome下出现部分css失效的问题,但是在ie和高版本的chrome中又没问题,当时还以为是css兼容性问题,后来发现失效的部分正是css文件中出现中文注释之后的样式,将中文注释去掉,则能够正常显示了。将css文件编码改为和页面编码相同(utf8)问题就解决了。还有页面之间中文参数传递时的编码和解码问题,搞web开发跟编码打交道的时间真多,有时候稍不注意就弄出乱码了。

猜你喜欢

转载自ygsilence.iteye.com/blog/2207932
今日推荐