問題提出:看了不少文章處理中文,比如:在 jsp里寫
//?傳統方式?

<%
@?page?contentType="text/html;?charset=gb2312"?%>?
<html>?
<body>?
<form?method=post?action=test.jsp>?
<input?type=text?name=your_name>?
</form>?
<%=?new?String(request.getParameter("your_name").getBytes("8859_1"),?"GB2312")?%>?
</body>?
</html>?

//?新的方式?

<%
@?page?contentType="text/html;?charset=gb2312"?%>?

<%
?request.setCharacterEncoding("GB2312");?%>?
<html>?
<body>?
<form?method=post?action=test.jsp>?
<input?type=text?name=your_name>?
</form>?
<%=?request.getParameter("your_name")?%>?
</body>?
</html>?那是相當不好的方法,現在介紹一個朋友教我的方法:
問題解決方法:
步驟1:先寫一個servlet? EncodingFilter.java
步驟2:在web.xml里這樣寫
<filter>
????????<filter-name>EncodingFilter</filter-name>
????????<display-name>EncodingFilter</display-name>
????????<filter-class>com.itthinker.payroll.common.EncodingFilter</filter-class>
????</filter>
????<filter-mapping>
????????<filter-name>EncodingFilter</filter-name>
????????<url-pattern>/*</url-pattern>
????</filter-mapping>
總結:
這樣的話,任何映射地址全部會先加載EncodingFilter,中文處理就搞定了,不用那么麻煩在每個jsp文件寫那么多重復代碼了,很好地做到了,代碼可復用性。當然?page?contentType="text/html;?charset=gb2312"
還是要的




























問題解決方法:
步驟1:先寫一個servlet? EncodingFilter.java
?1
import?javax.servlet.FilterChain;
?2
import?javax.servlet.ServletRequest;
?3
import?javax.servlet.ServletResponse;
?4
import?java.io.IOException;
?5
import?javax.servlet.Filter;
?6
import?javax.servlet.http.HttpServletRequest;
?7
import?javax.servlet.ServletException;
?8
import?javax.servlet.FilterConfig;
?9
10
public?class?EncodingFilter?implements?Filter?
{
11
12
????private?String?targetEncoding?=?"gb2312";
13
????protected?FilterConfig?filterConfig;
14
15
????public?void?init(FilterConfig?config)?throws?ServletException?
{
16
????????this.filterConfig?=?config;
17
????}
18
19
????public?void?doFilter(
20
????????ServletRequest?srequest,
21
????????ServletResponse?sresponse,
22
????????FilterChain?chain)
23
????????throws?IOException,?ServletException?
{
24
25
????????HttpServletRequest?request?=?(HttpServletRequest)?srequest;
26
????????request.setCharacterEncoding(targetEncoding);?//把請求用指定的方式編碼
27
????????//?把處理發送到下一個過濾器
28
????????chain.doFilter(srequest,?sresponse);
29
????}
30
31
????public?void?destroy()?
{
32
????????this.filterConfig?=?null;
33
????}
34
35
????public?void?setFilterConfig(final?FilterConfig?filterConfig)?
{
36
????????this.filterConfig?=?filterConfig;
37
????}
38
}
39

?2

?3

?4

?5

?6

?7

?8

?9

10



11

12

13

14

15



16

17

18

19

20

21

22

23



24

25

26

27

28

29

30

31



32

33

34

35



36

37

38

39

步驟2:在web.xml里這樣寫









總結:
這樣的話,任何映射地址全部會先加載EncodingFilter,中文處理就搞定了,不用那么麻煩在每個jsp文件寫那么多重復代碼了,很好地做到了,代碼可復用性。當然?page?contentType="text/html;?charset=gb2312"
還是要的