---
title: "常用filter"
author: "zhengxuezhou"
date: "2010-03-05T11:16:04Z"
tags: []
categories: ["编程语言"]
slug: "filter"
draft: false
lastmod: "2010-03-05T11:16:04Z"
id: 608524
url: "https://fire11.iteye.com/blog/608524"
---

出自：http://xxtianxiaxing.iteye.com/blog/350161 

在于自己收集好的东西，谢谢作者。 

Java代码 

   1. 五个有用的过滤器   
   2.   
   3. 一、使浏览器不缓存页面的过滤器      
   4. import javax.servlet.*;      
   5. import javax.servlet.http.HttpServletResponse;      
   6. import java.io.IOException;      
   7.      
   8. /**  
   9. * 用于的使 Browser 不缓存页面的过滤器  
  10. */     
  11. public class ForceNoCacheFilter implements Filter {      
  12.      
  13. public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException      
  14. {      
  15.     ((HttpServletResponse) response).setHeader("Cache-Control","no-cache");      
  16.     ((HttpServletResponse) response).setHeader("Pragma","no-cache");      
  17.     ((HttpServletResponse) response).setDateHeader ("Expires", -1);      
  18.     filterChain.doFilter(request, response);      
  19. }      
  20.      
  21. public void destroy()      
  22. {      
  23. }      
  24.      
  25.      public void init(FilterConfig filterConfig) throws ServletException      
  26. {      
  27. }      
  28. }      
  29.      
  30. 二、检测用户是否登陆的过滤器      
  31.      
  32. import javax.servlet.*;      
  33. import javax.servlet.http.HttpServletRequest;      
  34. import javax.servlet.http.HttpServletResponse;      
  35. import javax.servlet.http.HttpSession;      
  36. import java.util.List;      
  37. import java.util.ArrayList;      
  38. import java.util.StringTokenizer;      
  39. import java.io.IOException;      
  40.      
  41. /**  
  42. * 用于检测用户是否登陆的过滤器，如果未登录，则重定向到指的登录页面  
  43.  
  44.  
  45. * 配置参数  
  46.  
  47.  
  48. * checkSessionKey 需检查的在 Session 中保存的关键字  
  49.  
  50. * redirectURL 如果用户未登录，则重定向到指定的页面，URL不包括 ContextPath  
  51.  
  52. * notCheckURLList 不做检查的URL列表，以分号分开，并且 URL 中不包括 ContextPath  
  53.  
  54. */     
  55. public class CheckLoginFilter      
  56. implements Filter      
  57. {      
  58.      protected FilterConfig filterConfig = null;      
  59.      private String redirectURL = null;      
  60.      private List notCheckURLList = new ArrayList();      
  61.      private String sessionKey = null;      
  62.      
  63. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException      
  64. {      
  65.     HttpServletRequest request = (HttpServletRequest) servletRequest;      
  66.     HttpServletResponse response = (HttpServletResponse) servletResponse;      
  67.      
  68.      HttpSession session = request.getSession();      
  69.    if(sessionKey == null)      
  70.     {      
  71.      filterChain.doFilter(request, response);      
  72.     return;      
  73.     }      
  74.    if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)      
  75.     {      
  76.      response.sendRedirect(request.getContextPath() + redirectURL);      
  77.     return;      
  78.     }      
  79.     filterChain.doFilter(servletRequest, servletResponse);      
  80. }      
  81.      
  82. public void destroy()      
  83. {      
  84.     notCheckURLList.clear();      
  85. }      
  86.      
  87. private boolean checkRequestURIIntNotFilterList(HttpServletRequest request)      
  88. {      
  89.     String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());      
  90.    return notCheckURLList.contains(uri);      
  91. }      
  92.      
  93. public void init(FilterConfig filterConfig) throws ServletException      
  94. {      
  95.    this.filterConfig = filterConfig;      
  96.     redirectURL = filterConfig.getInitParameter("redirectURL");      
  97.     sessionKey = filterConfig.getInitParameter("checkSessionKey");      
  98.      
  99.     String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");      
100.      
101.    if(notCheckURLListStr != null)      
102.     {      
103.      StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");      
104.      notCheckURLList.clear();      
105.     while(st.hasMoreTokens())      
106.      {      
107.       notCheckURLList.add(st.nextToken());      
108.      }      
109.     }      
110. }      
111. }      
112.      
113. 三、字符编码的过滤器      
114.      
115. import javax.servlet.*;      
116. import java.io.IOException;      
117.      
118. /**  
119. * 用于设置 HTTP 请求字符编码的过滤器，通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题  
120. */     
121. public class CharacterEncodingFilter      
122. implements Filter      
123. {      
124. protected FilterConfig filterConfig = null;      
125. protected String encoding = "";      
126.      
127. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException      
128. {      
129.          if(encoding != null)      
130.            servletRequest.setCharacterEncoding(encoding);      
131.           filterChain.doFilter(servletRequest, servletResponse);      
132. }      
133.      
134. public void destroy()      
135. {      
136.     filterConfig = null;      
137.     encoding = null;      
138. }      
139.      
140.      public void init(FilterConfig filterConfig) throws ServletException      
141. {      
142.           this.filterConfig = filterConfig;      
143.          this.encoding = filterConfig.getInitParameter("encoding");      
144.      
145. }      
146. }      
147.      
148. 四、资源保护过滤器      
149.      
150.      
151. package catalog.view.util;      
152.      
153. import javax.servlet.Filter;      
154. import javax.servlet.FilterConfig;      
155. import javax.servlet.ServletRequest;      
156. import javax.servlet.ServletResponse;      
157. import javax.servlet.FilterChain;      
158. import javax.servlet.ServletException;      
159. import javax.servlet.http.HttpServletRequest;      
160. import java.io.IOException;      
161. import java.util.Iterator;      
162. import java.util.Set;      
163. import java.util.HashSet;      
164. //      
165. import org.apache.commons.logging.Log;      
166. import org.apache.commons.logging.LogFactory;      
167.      
168. /**  
169. * This Filter class handle the security of the application.  
170. *  
171. * It should be configured inside the web.xml.  
172. *  
173. * @author Derek Y. Shen  
174. */     
175. public class SecurityFilter implements Filter {      
176. //the login page uri      
177. private static final String LOGIN_PAGE_URI = "login.jsf";      
178.      
179. //the logger object      
180. private Log logger = LogFactory.getLog(this.getClass());      
181.      
182. //a set of restricted resources      
183. private Set restrictedResources;      
184.      
185. /**  
186.    * Initializes the Filter.  
187.    */     
188. public void init(FilterConfig filterConfig) throws ServletException {      
189.   this.restrictedResources = new HashSet();      
190.   this.restrictedResources.add("/createProduct.jsf");      
191.   this.restrictedResources.add("/editProduct.jsf");      
192.   this.restrictedResources.add("/productList.jsf");      
193. }      
194.      
195. /**  
196.    * Standard doFilter object.  
197.    */     
198. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)      
199.    throws IOException, ServletException {      
200.   this.logger.debug("doFilter");      
201.         
202.    String contextPath = ((HttpServletRequest)req).getContextPath();      
203.    String requestUri = ((HttpServletRequest)req).getRequestURI();      
204.         
205.   this.logger.debug("contextPath = " + contextPath);      
206.   this.logger.debug("requestUri = " + requestUri);      
207.         
208.   if (this.contains(requestUri, contextPath) && !this.authorize((HttpServletRequest)req)) {      
209.    this.logger.debug("authorization failed");      
210.     ((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res);      
211.    }      
212.   else {      
213.    this.logger.debug("authorization succeeded");      
214.     chain.doFilter(req, res);      
215.    }      
216. }      
217.      
218. public void destroy() {}      
219.      
220. private boolean contains(String value, String contextPath) {      
221.    Iterator ite = this.restrictedResources.iterator();      
222.         
223.   while (ite.hasNext()) {      
224.     String restrictedResource = (String)ite.next();      
225.          
226.    if ((contextPath + restrictedResource).equalsIgnoreCase(value)) {      
227.     return true;      
228.     }      
229.    }      
230.         
231.   return false;      
232. }      
233.      
234. private boolean authorize(HttpServletRequest req) {      
235.      
236.               //处理用户登录      
237.        /* UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);  
238.     
239.    if (user != null && user.getLoggedIn()) {  
240.     //user logged in  
241.     return true;  
242.    }  
243.    else {  
244.     return false;  
245.    }*/     
246. }      
247. }     
248. 五 利用Filter限制用户浏览权限   
249.   
250. 在一个系统中通常有多个权限的用户。不同权限用户的可以浏览不同的页面。使用Filter进行判断不仅省下了代码量，而且如果要更改的话只需要在Filter文件里动下就可以。   
251. 以下是Filter文件代码：   
252.   
253.   
254. import java.io.IOException;      
255.   
256.      
257. import javax.servlet.Filter;      
258. import javax.servlet.FilterChain;      
259. import javax.servlet.FilterConfig;      
260. import javax.servlet.ServletException;      
261. import javax.servlet.ServletRequest;      
262. import javax.servlet.ServletResponse;      
263. import javax.servlet.http.HttpServletRequest;      
264.      
265. public class RightFilter implements Filter {      
266.      
267.     public void destroy() {      
268.               
269.      }      
270.      
271.     public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain arg2) throws IOException, ServletException {      
272.         // 获取uri地址      
273.          HttpServletRequest request=(HttpServletRequest)sreq;      
274.          String uri = request.getRequestURI();      
275.          String ctx=request.getContextPath();      
276.          uri = uri.substring(ctx.length());      
277.         //判断admin级别网页的浏览权限      
278.         if(uri.startsWith("/admin")) {      
279.             if(request.getSession().getAttribute("admin")==null) {      
280.                  request.setAttribute("message","您没有这个权限");      
281.                  request.getRequestDispatcher("/login.jsp").forward(sreq,sres);      
282.                 return;      
283.              }      
284.          }      
285.         //判断manage级别网页的浏览权限      
286.         if(uri.startsWith("/manage")) {      
287.             //这里省去      
288.              }      
289.          }      
290.         //下面还可以添加其他的用户权限，省去。      
291.      
292.      }      
293.      
294.     public void init(FilterConfig arg0) throws ServletException {      
295.               
296.      }      
297.      
298. }   
299.   
300. <!-- 判断页面的访问权限 -->     
301.   <filter>     
302.      <filter-name>RightFilter</filter-name>     
303.       <filter-class>cn.itkui.filter.RightFilter</filter-class>     
304.   </filter>     
305.   <filter-mapping>     
306.       <filter-name>RightFilter</filter-name>     
307.       <url-pattern>/admin/*</url-pattern>     
308.   </filter-mapping>     
309.   <filter-mapping>     
310.       <filter-name>RightFilter</filter-name>     
311.       <url-pattern>/manage/*</url-pattern>     
312.   </filter-mapping>     
313.   
314. 在web.xml中加入Filter的配置，如下：   
315. <filter>     
316.   
317.         <filter-name>EncodingAndCacheflush</filter-name>     
318.         <filter-class>EncodingAndCacheflush</filter-class>     
319.         <init-param>     
320.             <param-name>encoding</param-name>     
321.             <param-value>UTF-8</param-value>     
322.         </init-param>     
323.     </filter>     
324.     <filter-mapping>     
325.         <filter-name>EncodingAndCacheflush</filter-name>     
326.         <url-pattern>/*</url-pattern>     
327.     </filter-mapping>     
328. 要传递参数的时候最好使用form进行传参，如果使用链接的话当中文字符的时候过滤器转码是不会起作用的，还有就是页面上   
329.   
330. form的method也要设置为post，不然过滤器也起不了作用。