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