【分享】过滤器设置编码

看到的很简单的过滤器设置编码,分享下~

过滤器的代码:

01importjava.io.IOException;
02
03importjavax.servlet.Filter;
04importjavax.servlet.FilterChain;
05importjavax.servlet.FilterConfig;
06importjavax.servlet.ServletException;
07importjavax.servlet.ServletRequest;
08importjavax.servlet.ServletResponse;
09
10/**
11* 处理乱码的Filter
12* tomcat处理提交的参数时默认的是iso-8859-1,所以需要加以处理。
13*/
14publicclassEncodingFilter implementsFilter
15{
16protectedString encoding = null;
17protectedFilterConfig filterConfig = null;
18protectedbooleanignore = true;
19
20publicvoiddestroy()
21{
22this.encoding = null;
23this.filterConfig = null;
24}
25
26publicvoiddoFilter(ServletRequest request, ServletResponse response,
27FilterChain chain) throwsIOException, ServletException
28{
29if(ignore || (request.getCharacterEncoding() == null))
30{
31String encoding = selectEncoding(request);
32if(encoding != null)
33{
34request.setCharacterEncoding(encoding);
35}
36}
37// Pass control on to the next filter
38chain.doFilter(request, response);
39}
40
41publicvoidinit(FilterConfig filterConfig) throwsServletException
42{
43this.filterConfig = filterConfig;
44this.encoding = filterConfig.getInitParameter("encoding");
45String value = filterConfig.getInitParameter("ignore");
46if(value == null)
47{
48this.ignore = true;
49}
50elseif(value.equalsIgnoreCase("true"))
51{
52this.ignore = true;
53}
54elseif(value.equalsIgnoreCase("yes"))
55{
56this.ignore = true;
57}
58else
59{
60this.ignore = false;
61}
62}
63
64protectedString selectEncoding(ServletRequest request)
65{
66return(this.encoding);
67}
68}
web.xml中配置如下:
01<filter>
02<filter-name>Encoding</filter-name>
03<filter-class>
04com.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>

你可能感兴趣的:(设置编码)