在網上有很多有關Struts的中文解決方案,但是很多都說得很零碎,不夠完整。下面是我的一個完整解決方案。
要使網頁能夠真正實現多語言,有三個地方都需要修改:
1.在頁面部分,一定要把頁面的編碼設成UTF-8,就是在開頭加上這一句:<%@ page contentType="text/html; charset=UTF-8" %>。并且把所有的文字信息都放到resource文件中。
以前我在寫網頁的時候,沒有指定頁面的編碼,總是在獲取表單的內容后,要人工的用new String(s.getBytes("ISO8859-1"))轉換一下,這樣是很繁瑣的,而且很容易出錯。網頁中如果沒有指定編碼,那么默認的就是用ISO8859-1編碼的。
2.相應的資源文件需要用native2ascii轉換一下。
對于簡體中文的資源文件:native2ascii -encoding gbk ApplicationResources_zh.properties convert\ApplicationResources_zh.properties
對于繁體中文的資源文件:native2ascii -encoding big5 ApplicationResources_zh_tw.properties convert\ApplicationResources_zh_tw.properties
3.需要用一個filter設置一下request的編碼,我的代碼如下:
1
import java.io.*;
2
import java.util.*;
3
import javax.servlet.*;
4
import javax.servlet.http.*;
5
6
/**//**
7
* <p>Title: </p>
8
* <p>Description: </p>
9
* <p>Copyright: Copyright (c) 2003</p>
10
* <p>Company: </p>
11
* @author George Hill
12
* @version 1.0
13
*/
14
15
public class CharsetFilter implements Filter
{
16
17
private FilterConfig filterConfig;
18
19
/**//**
20
* Request設置的Charset encoding
21
*/
22
private String encoding;
23
24
/**//**
25
* 是否忽略設置Request的Charset encoding
26
*/
27
private boolean ignore;
28
29
//Handle the passed-in FilterConfig
30
public void init(FilterConfig filterConfig)
{
31
this.filterConfig = filterConfig;
32
33
encoding = filterConfig.getInitParameter("encoding");
34
String value = filterConfig.getInitParameter("ignore");
35
if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value)
36
|| "on".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))
{
37
ignore = true;
38
}
39
}
40
41
//Process the request/response pair
42
public void doFilter(ServletRequest request, ServletResponse response,
43
FilterChain chain) throws IOException, ServletException
{
44
if (!ignore)
{
45
request.setCharacterEncoding(encoding);
46
}
47
48
chain.doFilter(request, response);
49
}
50
51
//Clean up resources
52
public void destroy()
{
53
this.filterConfig = null;
54
}
55
}
56
web.xml的相關片斷如下:
1
<filter>
2
<filter-name>charsetfilter</filter-name>
3
<filter-class>xxx.CharsetFilter</filter-class>
4
<init-param>
5
<param-name>encoding</param-name>
6
<param-value>UTF-8</param-value>
7
</init-param>
8
<init-param>
9
<param-name>ignore</param-name>
10
<param-value>false</param-value>
11
</init-param>
12
</filter>
13
<filter-mapping>
14
<filter-name>charsetfilter</filter-name>
15
<url-pattern>/*</url-pattern>
16
</filter-mapping>
這樣,在Action中處理表達的內容時,就不需要再做轉換;而且在Action中處理數據給頁面顯示時,也不需要做轉換。在頁面中可以同時顯示簡體和繁體的內容,不需要去設置IE的編碼。
另外需要說明的就是如果數據庫也支持編碼的話,最好也是設成UTF-8編碼,這樣才能夠完整的解決多語言的問題。例如MySQL 4.1以上的版本可以設置編碼成utf8,在JDBC的URL中可以指定編碼為UTF-8。
]]>