Hibernate3+mysql4 中文问题解决方案.

1, mysql安装时设置字符集utf-8(包括数据库字符集,以及表的字符集), jdbc驱动用最新的
2. hibernate配置文件(hibernate.cfg.xml)中,加上属性
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>

3. web.xml设置Filter
=================================================
< filter >
  
< filter-name >
   Set Web Application Character Encoding
  
</ filter-name >
  
< filter-class >com.util. SetEncodeFilter </ filter-class >
  
< init-param >
   
< param-name > defaultencoding </ param-name >
   
< param-value > UTF-8 </ param-value >
  
</ init-param >
 
</ filter >
 
< filter-mapping >
  
< filter-name >
   Set Web Application Character Encoding
  
</ filter-name >
  
< url-pattern > /* </ url-pattern >
 
</ filter-mapping >


=============================================
SetEncodeFilter.java

 1 package  com.util;
 2
 3 import  java.io.IOException;
 4
 5 import  javax.servlet.Filter;
 6 import  javax.servlet.FilterChain;
 7 import  javax.servlet.FilterConfig;
 8 import  javax.servlet.ServletException;
 9 import  javax.servlet.ServletRequest;
10 import  javax.servlet.ServletResponse;
11
12 public   class  SetEncodeFilter  implements  Filter 
13     
14    protected FilterConfig filterConfig = null
15 
16    protected String defaultEncoding = null
17 
18    /** *//**//* (non-Javadoc) 
19     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) 
20     */
 
21    public void init(FilterConfig arg0) throws ServletException 
22        // TODO Auto-generated method stub 
23        this.filterConfig = arg0; 
24        this.defaultEncoding = filterConfig.getInitParameter("defaultencoding"); 
25    }
 
26 
27    /** *//**//* (non-Javadoc) 
28     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) 
29     */
 
30    public void doFilter( 
31        ServletRequest request, 
32        ServletResponse response, 
33        FilterChain chain) 
34        throws IOException, ServletException 
35        // TODO Auto-generated method stub 
36        request.setCharacterEncoding(selectEncoding(request)); 
37        chain.doFilter(request, response); 
38    }
 
39 
40 
41    public void destroy() 
42         
43        this.defaultEncoding = null
44        this.filterConfig = null
45    }
 
46 
47 
48    protected String selectEncoding(ServletRequest request) 
49 
50        return this.defaultEncoding; 
51    }
 
52 
53}
 

 

4.提交表单的jsp页面设置
<%@ page language="java"  contentType="text/html; charset=UTF-8"%>

你可能感兴趣的:(Hibernate3+mysql4 中文问题解决方案.)