看到的很简单的过滤器设置编码,分享下~
过滤器的代码:
01
import
java.io.IOException;
02
03
import
javax.servlet.Filter;
04
import
javax.servlet.FilterChain;
05
import
javax.servlet.FilterConfig;
06
import
javax.servlet.ServletException;
07
import
javax.servlet.ServletRequest;
08
import
javax.servlet.ServletResponse;
09
10
/**
11
* 处理乱码的Filter
12
* tomcat处理提交的参数时默认的是iso-8859-1,所以需要加以处理。
13
*/
14
public
class
EncodingFilter
implements
Filter
15
{
16
protected
String encoding =
null
;
17
protected
FilterConfig filterConfig =
null
;
18
protected
boolean
ignore =
true
;
19
20
public
void
destroy()
21
{
22
this
.encoding =
null
;
23
this
.filterConfig =
null
;
24
}
25
26
public
void
doFilter(ServletRequest request, ServletResponse response,
27
FilterChain chain)
throws
IOException, ServletException
28
{
29
if
(ignore || (request.getCharacterEncoding() ==
null
))
30
{
31
String encoding = selectEncoding(request);
32
if
(encoding !=
null
)
33
{
34
request.setCharacterEncoding(encoding);
35
}
36
}
37
// Pass control on to the next filter
38
chain.doFilter(request, response);
39
}
40
41
public
void
init(FilterConfig filterConfig)
throws
ServletException
42
{
43
this
.filterConfig = filterConfig;
44
this
.encoding = filterConfig.getInitParameter(
"encoding"
);
45
String value = filterConfig.getInitParameter(
"ignore"
);
46
if
(value ==
null
)
47
{
48
this
.ignore =
true
;
49
}
50
else
if
(value.equalsIgnoreCase(
"true"
))
51
{
52
this
.ignore =
true
;
53
}
54
else
if
(value.equalsIgnoreCase(
"yes"
))
55
{
56
this
.ignore =
true
;
57
}
58
else
59
{
60
this
.ignore =
false
;
61
}
62
}
63
64
protected
String selectEncoding(ServletRequest request)
65
{
66
return
(
this
.encoding);
67
}
68
}
web.xml中配置如下:
01
<
filter
>
02
<
filter-name
>Encoding</
filter-name
>
03
<
filter-class
>
04
com.util.encoding.EncodingFilter
05
</
filter-class
>
06
<
init-param
>
07
<
param-name
>encoding</
param-name
>
08
<
param-value
>UTF-8</
param-value
>
09
</
init-param
>
10
</
filter
>
11
12
<
filter-mapping
>
13
<
filter-name
>Encoding</
filter-name
>
14
<
url-pattern
>/*</
url-pattern
>
15
</
filter-mapping
>