Chinaunix首页 | 论坛 | 博客
  • 博客访问: 30392200
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2008-05-28 15:46:16

  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, ServletException   
  12. {   
  13.    ((HttpServletResponse) response).setHeader("Cache-Control","no-cache");   
  14.    ((HttpServletResponse) response).setHeader("Pragma","no-cache");   
  15.    ((HttpServletResponse) response).setDateHeader ("Expires", -1);   
  16.    filterChain.doFilter(request, response);   
  17. }   
  18.   
  19. public void destroy()   
  20. {   
  21. }   
  22.   
  23.      public void init(FilterConfig filterConfig) throws ServletException   
  24. {   
  25. }   
  26. }   
  27.   
  28. 二、检测用户是否登陆的过滤器   
  29.   
  30. import javax.servlet.*;   
  31. import javax.servlet.http.HttpServletRequest;   
  32. import javax.servlet.http.HttpServletResponse;   
  33. import javax.servlet.http.HttpSession;   
  34. import java.util.List;   
  35. import java.util.ArrayList;   
  36. import java.util.StringTokenizer;   
  37. import java.io.IOException;   
  38.   
  39. /**  
  40. * 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面   
  41. * 配置参数   
  42. * checkSessionKey 需检查的在 Session 中保存的关键字  
  43. * redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath  
  44. * notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath  
  45. */  
  46. public class CheckLoginFilter   
  47. implements Filter   
  48. {   
  49.      protected FilterConfig filterConfig = null;   
  50.      private String redirectURL = null;   
  51.      private List notCheckURLList = new ArrayList();   
  52.      private String sessionKey = null;   
  53.   
  54. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException   
  55. {   
  56.    HttpServletRequest request = (HttpServletRequest) servletRequest;   
  57.    HttpServletResponse response = (HttpServletResponse) servletResponse;   
  58.   
  59.     HttpSession session = request.getSession();   
  60.    if(sessionKey == null)   
  61.    {   
  62.     filterChain.doFilter(request, response);   
  63.     return;   
  64.    }   
  65.    if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)   
  66.    {   
  67.     response.sendRedirect(request.getContextPath() + redirectURL);   
  68.     return;   
  69.    }   
  70.    filterChain.doFilter(servletRequest, servletResponse);   
  71. }   
  72.   
  73. public void destroy()   
  74. {   
  75.    notCheckURLList.clear();   
  76. }   
  77.   
  78. private boolean checkRequestURIIntNotFilterList(HttpServletRequest request)   
  79. {   
  80.    String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());   
  81.    return notCheckURLList.contains(uri);   
  82. }   
  83.   
  84. public void init(FilterConfig filterConfig) throws ServletException   
  85. {   
  86.    this.filterConfig = filterConfig;   
  87.    redirectURL = filterConfig.getInitParameter("redirectURL");   
  88.    sessionKey = filterConfig.getInitParameter("checkSessionKey");   
  89.   
  90.    String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");   
  91.   
  92.    if(notCheckURLListStr != null)   
  93.    {   
  94.     StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");   
  95.     notCheckURLList.clear();   
  96.     while(st.hasMoreTokens())   
  97.     {   
  98.      notCheckURLList.add(st.nextToken());   
  99.     }   
  100.    }   
  101. }   
  102. }   
  103.   
  104. 三、字符编码的过滤器   
  105.   
  106. import javax.servlet.*;   
  107. import java.io.IOException;   
  108.   
  109. /**  
  110. * 用于设置 HTTP 请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题  
  111. */  
  112. public class CharacterEncodingFilter   
  113. implements Filter   
  114. {   
  115. protected FilterConfig filterConfig = null;   
  116. protected String encoding = "";   
  117.   
  118. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException   
  119. {   
  120.          if(encoding != null)   
  121.           servletRequest.setCharacterEncoding(encoding);   
  122.          filterChain.doFilter(servletRequest, servletResponse);   
  123. }   
  124.   
  125. public void destroy()   
  126. {   
  127.    filterConfig = null;   
  128.    encoding = null;   
  129. }   
  130.   
  131.      public void init(FilterConfig filterConfig) throws ServletException   
  132. {   
  133.           this.filterConfig = filterConfig;   
  134.          this.encoding = filterConfig.getInitParameter("encoding");   
  135.   
  136. }   
  137. }   
  138.   
  139. 四、资源保护过滤器   
  140.   
  141.   
  142. package catalog.view.util;   
  143.   
  144. import javax.servlet.Filter;   
  145. import javax.servlet.FilterConfig;   
  146. import javax.servlet.ServletRequest;   
  147. import javax.servlet.ServletResponse;   
  148. import javax.servlet.FilterChain;   
  149. import javax.servlet.ServletException;   
  150. import javax.servlet.http.HttpServletRequest;   
  151. import java.io.IOException;   
  152. import java.util.Iterator;   
  153. import java.util.Set;   
  154. import java.util.HashSet;   
  155. //   
  156. import org.apache.commons.logging.Log;   
  157. import org.apache.commons.logging.LogFactory;   
  158.   
  159. /**  
  160.  * This Filter class handle the security of the application.  
  161.  *   
  162.  * It should be configured inside the web.xml.  
  163.  *   
  164.  * @author Derek Y. Shen  
  165.  */  
  166. public class SecurityFilter implements Filter {   
  167.  //the login page uri   
  168.  private static final String LOGIN_PAGE_URI = "login.jsf";   
  169.     
  170.  //the logger object   
  171.  private Log logger = LogFactory.getLog(this.getClass());   
  172.     
  173.  //a set of restricted resources   
  174.  private Set restrictedResources;   
  175.     
  176.  /**  
  177.   * Initializes the Filter.  
  178.   */  
  179.  public void init(FilterConfig filterConfig) throws ServletException {   
  180.   this.restrictedResources = new HashSet();   
  181.   this.restrictedResources.add("/createProduct.jsf");   
  182.   this.restrictedResources.add("/editProduct.jsf");   
  183.   this.restrictedResources.add("/productList.jsf");   
  184.  }   
  185.     
  186.  /**  
  187.   * Standard doFilter object.  
  188.   */  
  189.  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)   
  190.    throws IOException, ServletException {   
  191.   this.logger.debug("doFilter");   
  192.      
  193.   String contextPath = ((HttpServletRequest)req).getContextPath();   
  194.   String requestUri = ((HttpServletRequest)req).getRequestURI();   
  195.      
  196.   this.logger.debug("contextPath = " + contextPath);   
  197.   this.logger.debug("requestUri = " + requestUri);   
  198.      
  199.   if (this.contains(requestUri, contextPath) && !this.authorize((HttpServletRequest)req)) {   
  200.    this.logger.debug("authorization failed");   
  201.    ((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res);   
  202.   }   
  203.   else {   
  204.    this.logger.debug("authorization succeeded");   
  205.    chain.doFilter(req, res);   
  206.   }   
  207.  }   
  208.     
  209.  public void destroy() {}    
  210.     
  211.  private boolean contains(String value, String contextPath) {   
  212.   Iterator ite = this.restrictedResources.iterator();   
  213.      
  214.   while (ite.hasNext()) {   
  215.    String restrictedResource = (String)ite.next();   
  216.       
  217.    if ((contextPath + restrictedResource).equalsIgnoreCase(value)) {   
  218.     return true;   
  219.    }   
  220.   }   
  221.      
  222.   return false;   
  223.  }   
  224.     
  225.  private boolean authorize(HttpServletRequest req) {   
  226.   
  227.               //处理用户登录   
  228.        /* UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);  
  229.     
  230.   if (user != null && user.getLoggedIn()) {  
  231.    //user logged in  
  232.    return true;  
  233.   }  
  234.   else {  
  235.    return false;  
  236.   }*/  
  237.  }   
  238. }  

利用Filter限制用户浏览权限

在一个系统中通常有多个权限的用户。不同权限用户的可以浏览不同的页面。使用Filter进行判断不仅省下了代码量,而且如果要更改的话只需要在Filter文件里动下就可以。
以下是Filter文件代码:

  1. import java.io.IOException;   
  2.   
  3. import javax.servlet.Filter;   
  4. import javax.servlet.FilterChain;   
  5. import javax.servlet.FilterConfig;   
  6. import javax.servlet.ServletException;   
  7. import javax.servlet.ServletRequest;   
  8. import javax.servlet.ServletResponse;   
  9. import javax.servlet.http.HttpServletRequest;   
  10.   
  11. public class RightFilter implements Filter {   
  12.   
  13.     public void destroy() {   
  14.            
  15.     }   
  16.   
  17.     public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain arg2) throws IOException, ServletException {   
  18.         // 获取uri地址   
  19.         HttpServletRequest request=(HttpServletRequest)sreq;   
  20.         String uri = request.getRequestURI();   
  21.         String ctx=request.getContextPath();   
  22.         uri = uri.substring(ctx.length());   
  23.         //判断admin级别网页的浏览权限   
  24.         if(uri.startsWith("/admin")) {   
  25.             if(request.getSession().getAttribute("admin")==null) {   
  26.                 request.setAttribute("message","您没有这个权限");   
  27.                 request.getRequestDispatcher("/login.jsp").forward(sreq,sres);   
  28.                 return;   
  29.             }   
  30.         }   
  31.         //判断manage级别网页的浏览权限   
  32.         if(uri.startsWith("/manage")) {   
  33.             //这里省去   
  34.             }   
  35.         }   
  36.         //下面还可以添加其他的用户权限,省去。   
  37.   
  38.     }   
  39.   
  40.     public void init(FilterConfig arg0) throws ServletException {   
  41.            
  42.     }   
  43.   
  44. }  
  45.   
  46.   <filter>  
  47.      <filter-name>RightFilterfilter-name>  
  48.       <filter-class>cn.itkui.filter.RightFilterfilter-class>  
  49.   filter>  
  50.   <filter-mapping>  
  51.       <filter-name>RightFilterfilter-name>  
  52.       <url-pattern>/admin/*url-pattern>  
  53.   filter-mapping>  
  54.   <filter-mapping>  
  55.       <filter-name>RightFilterfilter-name>  
  56.       <url-pattern>/manage/*url-pattern>  
  57.   filter-mapping>  
  58.  
  59. 在web.xml中加入Filter的配置,如下:
  60. <filter>  
  61.         <filter-name>EncodingAndCacheflushfilter-name>  
  62.         <filter-class>EncodingAndCacheflushfilter-class>  
  63.         <init-param>  
  64.             <param-name>encodingparam-name>  
  65.             <param-value>UTF-8param-value>  
  66.         init-param>  
  67.     filter>  
  68.     <filter-mapping>  
  69.         <filter-name>EncodingAndCacheflushfilter-name>  
  70.         <url-pattern>/*url-pattern>  
  71.     filter-mapping>  
  72. 要传递参数的时候最好使用form进行传参,如果使用链接的话当中文字符的时候过滤器转码是不会起作用的,还有就是页面上

    form的method也要设置为post,不然过滤器也起不了作用。

阅读(2102) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~