首先在web.xml中配置监听,如下:
<? xml version = "1.0" encoding = "UTF-8" ?> |
02 | < web-app version = "3.0" xmlns = "http://java.sun.com/xml/ns/javaee" |
03 | xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" |
04 | xsi:schemaLocation="http://java.sun.com/xml/ns/javaee |
05 | http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> |
06 | < display-name ></ display-name > |
07 | |
08 | < filter > |
09 | < filter-name >encodingFilter</ filter-name > |
10 | < filter-class >com.cqcet.filter.EncodeFilter</ filter-class > |
11 | < init-param > |
12 | < param-name >encoding</ param-name > |
13 | < param-value >UTF-8</ param-value > |
14 | </ init-param > |
15 | </ filter > |
16 | < filter-mapping > |
17 | < filter-name >encodingFilter</ filter-name > |
18 | < url-pattern >/*</ url-pattern > |
19 | < dispatcher >FORWARD</ dispatcher > |
20 | < dispatcher >REQUEST</ dispatcher > |
21 | </ filter-mapping > |
22 | </ web-app > |
然后在src下编写过滤器:
package com.cqcet.filter; |
02 | |
03 | import java.io.IOException; |
04 | |
05 | import javax.servlet.Filter; |
06 | import javax.servlet.FilterChain; |
07 | import javax.servlet.FilterConfig; |
08 | import javax.servlet.ServletException; |
09 | import javax.servlet.ServletRequest; |
10 | import javax.servlet.ServletResponse; |
11 | //实现字符编码过滤 |
12 | public class EncodeFilter implements Filter { |
13 | protected String encoding = null ; |
14 | protected FilterConfig filterConfig = null ; |
15 | |
16 | public void destroy() { |
17 | System.out.println( "过滤器销毁!" ); |
18 | this .encoding = null ; |
19 | this .filterConfig = null ; |
20 | |
21 | } |
22 | |
23 | public void doFilter(ServletRequest request, ServletResponse response, |
24 | FilterChain chain) throws IOException, ServletException { |
25 | String encoding = this .encoding; |
26 | if (encoding != null ) { |
27 | request.setCharacterEncoding(encoding); |
28 | } else { |
29 | request.setCharacterEncoding( "UTF-8" ); |
30 | } |
31 | chain.doFilter(request, response); // 传递过滤链 |
32 | |
33 | } |
34 | |
35 | public void init(FilterConfig config) throws ServletException { |
36 | System.out.println( "过滤器初始化!" ); |
37 | this .filterConfig = config; |
38 | this .encoding = filterConfig.getInitParameter( "encoding" ); // 获取传递过来的初使化编码 |
39 | |
40 | } |
41 | |
42 | } |