1 package cqvie.yjq.filter;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13
14 public class EncodingFilter1 implements Filter {
15
16 public void destroy() {
17
18 }
19
20 public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
21 throws IOException, ServletException {
22
23 //1.首先ServletRequest转换为HttpServletRequest
24 HttpServletRequest request = (HttpServletRequest) arg0;
25 //2.把ServletResponse转换为HttpServletResponse
26 HttpServletResponse response = (HttpServletResponse) arg1;
27 //3.得到当前的请求方式
28 String method = request.getMethod();
29 //4.判断
30 if(method.toUpperCase().equals("POST")) {
31 //是post请求时,处理乱码
32 request.setCharacterEncoding("UTF-8");
33 //放行
34 chain.doFilter(request, response);
35 } else {
36 chain.doFilter(request, response);
37 }
38 }
39
40 public void init(FilterConfig arg0) throws ServletException {
41
42 }
43
44 }
1 <!-- 为了防止乱码,基于web.xml中的部分关于过滤器的配置 -->
2 <filter>
3 <filter-name>EncodingFilter1</filter-name>
4 <filter-class>cqvie.yjq.filter.EncodingFilter1</filter-class>
5 </filter>
6
7 <filter-mapping>
8 <filter-name>EncodingFilter1</filter-name>
9 <!-- 所有路径的文件 -->
10 <url-pattern>/*</url-pattern>
11 </filter-mapping>
web.xml