Hibernate+MySQL5.0結合的默認配置,那麼向數據庫寫入中文數據的時候會是亂碼,且jsp頁面顯示中文的時候也有有亂碼問題,非常煩人。
通過查詢及整理,處理方法以下:
一、修改hibernate的配置文件,在url處添加綠色的一段:
<
hibernate-configuration
>
<
session-factory
name
="myjava"
>
<
property
name
="hibernate.connection.driver_class"
>org.gjt.mm.mysql.Driver
</
property
>
<
property
name
="hibernate.connection.url"
>jdbc:mysql://localhost:3306/myjava
?useUnicode=true&characterEncoding=UTF-8
</
property
>
<
property
name
="hibernate.connection.username"
>root
</
property
>
<
property
name
="hibernate.connection.password"
>test
</
property
>
<
property
name
="connection.pool_size"
>10
</
property
>
<
property
name
="hibernate.dialect"
>org.hibernate.dialect.MySQL5Dialect
</
property
>
<
property
name
="current_session_context_class"
>thread
</
property
>
<
property
name
="cache.provider_class"
>org.hibernate.cache.NoCacheProvider
</
property
>
<
property
name
="show_sql"
>true
</
property
>
<
property
name
="hbm2ddl.auto"
>create
</
property
>
</
session-factory
>
</
hibernate-configuration
>
二、jsp頁面設置語言,同時form表單使用post方式提交
<
html
>
<
head
>
<
meta
http-equiv
="Content-Type"
content
="text/html;charset=UTF-8"
>
<
title
>Event Manager
</title>
</head>
<
body
>
<
form
method
="post"
>
...
</form>
</body>
</html>
三、建立一個語言過濾servlet,用來處理請求和發送的字符編碼
(1)CharacterEncodingFilter.java文件的源碼以下:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
@SuppressWarnings(
"serial")
public
class CharacterEncodingFilter
extends HttpServlet
implements Filter {
public CharacterEncodingFilter() {
// TODO Auto-generated constructor stub
}
public
void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2)
throws IOException, ServletException {
//下面的兩個編碼根據你的項目所使用的中文字符集肯定
arg0.setCharacterEncoding(
"UTF-8");
arg1.setCharacterEncoding(
"UTF-8");
arg2.doFilter(arg0, arg1);
}
}
(2)WEB-INF/web.xml文件修改以下:
<?
xml
version
="1.0"
encoding
="UTF-8"
?>
<
web-app
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
xmlns
="http://java.sun.com/xml/ns/javaee"
xmlns:web
="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation
="http://java.sun.com/xml/ns/javaee [url]http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd[/url]"
id
="WebApp_ID"
version
="2.5"
>
<
filter
>
<
filter-name
>CharacterEncodingFilter
</
filter-name
>
<
filter-class
>events.CharacterEncodingFilter
</
filter-class
>
</
filter
>
<
filter-mapping
>
<
filter-name
>CharacterEncodingFilter
</
filter-name
>
<
url-pattern
>/*
</
url-pattern
>
</
filter-mapping
>
<
welcome-file-list
>
<
welcome-file
>index.html
</
welcome-file
>
<
welcome-file
>index.htm
</
welcome-file
>
<
welcome-file
>index.jsp
</
welcome-file
>
</
welcome-file-list
>
</
web-app
>
到此,hibernate和mysql結合的中文存儲亂碼問題,jsp頁面顯示中文問題就解決了。若是你的應用仍是有亂碼問題,那就要詳細對應問題狀況,而後再處理問題了。