码迷,mamicode.com
首页 > 其他好文 > 详细

过滤器(防止乱码)

时间:2016-12-01 01:44:09      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:ica   lte   port   etc   cep   pat   post请求   row   --   

 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

 

过滤器(防止乱码)

标签:ica   lte   port   etc   cep   pat   post请求   row   --   

原文地址:http://www.cnblogs.com/yjq520/p/6119815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!