Servlet过滤器详解
一、过滤器基础
1.Servlet过滤器是Servlet的一种特殊用法,主要用来完成一些通用的操作。比如编码的过滤,判断用户的登陆状态等等。Servlet过滤器的适用场合:
A.认证过滤
B.登录和审核过滤
C.图像转换过滤
D.数据压缩过滤
E.加密过滤
F.令牌过滤
G.资源访问触发事件过滤
2.Servlet过滤器接口的构成:
所有的Servlet过滤器类都必须实现javax.servlet.Filter接口。这个接口含有3个过滤器类必须实现的方法:
方法 说明
init(FilterConfig cfg) 这是Servlet过滤器的初始化方法,性质等同与servlet的init方法。
doFilter(ServletRequest,ServletResponse,FilterChain) 完成实际的过滤操作,当请求访问过滤器关联的URL时,Servlet容器将先调用过滤器的doFilter方法。FilterChain参数用于访问后续过滤器
destroy() Servlet容器在销毁过滤器实例前调用该方法,这个方法中可以释放Servlet过滤器占用的资源。,性质等同与servlet的destory()方法。
3.Servlet过滤器的创建步骤:
A.实现javax.servlet.Filter接口的servlet类
B.实现init方法,读取过滤器的初始化函数
C.实现doFilter方法,完成对请求或过滤的响应
D.调用FilterChain接口对象的doFilter方法,向后续的过滤器传递请求或响应
F.在web.xml中配置Filter
二、使用过滤器处理中文问题
当用用户登陆页面输入帐号时,如果输入是中文,后台servlet再次输出这个内容时,可能就会是乱码,这是因为serlvet中默认是以ISO-8859-1格式编码的,如果后台有多个Servlet,多个参数,这样就不合适,这个问题,我们可以通过一个过滤器统一解决,使后台的输出输出都支持中文!将ISO-8859-1转码为GBK的那段代码!
三、使用过滤器认证用户
每个过滤器也可以配置初始化参数,可以将不需要过滤的地址配置到这个Filter的配置参数中,过滤时,如果请求地址在配置参数中,则放行,这样 就避免了在程序中硬编码。每个Filter中初始化时,都可以得到配置对象,在Filter中配置二个不需要过滤的地址,一个是登陆页面,一个是执行登陆 认证的servlet;
四、Servlet监听器
类似与Swing界面应用开发,Servlet也可以创建监听器,以对Servlet容器,或Servlet中以象的事件做出反应。Servlet监听器主要有以下几种:
ServletRequestListener ,ServletRequestAttributeListener,
HttpSessionActivationListener ,HttpSessionBindingListener ,
HttpSessionAttributeListener,HttpSessionListener,
ServletContextListener等等。
这些监听器主要用来监听session,request,application这三个对象里存取数据的变化。
五、五个有用的过滤器
1、使浏览器不缓存页面的过滤器
import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 用于的使 Browser 不缓存页面的过滤器 */ public class ForceNoCacheFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { ((HttpServletResponse) response).setHeader("Cache-Control","no-cache"); ((HttpServletResponse) response).setHeader("Pragma","no-cache"); ((HttpServletResponse) response).setDateHeader ("Expires", -1); filterChain.doFilter(request, response); } public void destroy() { } public void init(FilterConfig filterConfig) throws ServletException { } }
2、检测用户是否登陆的过滤器
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.List; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.IOException; /** * 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面 * 配置参数 * checkSessionKey 需检查的在 Session 中保存的关键字 * redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath * notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath */ public class CheckLoginFilter implements Filter { protected FilterConfig filterConfig = null; private String redirectURL = null; private List notCheckURLList = new ArrayList(); private String sessionKey = null; public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); if(sessionKey == null) { filterChain.doFilter(request, response); return; } if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null) { response.sendRedirect(request.getContextPath() + redirectURL); return; } filterChain.doFilter(servletRequest, servletResponse); } public void destroy() { notCheckURLList.clear(); } private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) { String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo()); return notCheckURLList.contains(uri); } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; redirectURL = filterConfig.getInitParameter("redirectURL"); sessionKey = filterConfig.getInitParameter("checkSessionKey"); String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList"); if(notCheckURLListStr != null) { StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";"); notCheckURLList.clear(); while(st.hasMoreTokens()) { notCheckURLList.add(st.nextToken()); } } } }
3、字符编码的过滤器
1 import javax.servlet.*; 2 import java.io.IOException; 3 4 /** 5 * 用于设置 HTTP 请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题 6 */ 7 public class CharacterEncodingFilter 8 implements Filter 9 { 10 protected FilterConfig filterConfig = null; 11 protected String encoding = ""; 12 13 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException 14 { 15 if(encoding != null) 16 servletRequest.setCharacterEncoding(encoding); 17 filterChain.doFilter(servletRequest, servletResponse); 18 } 19 20 public void destroy() 21 { 22 filterConfig = null; 23 encoding = null; 24 } 25 26 public void init(FilterConfig filterConfig) throws ServletException 27 { 28 this.filterConfig = filterConfig; 29 this.encoding = filterConfig.getInitParameter("encoding"); 30 31 } 32 }
4、资源保护过滤器
1 import javax.servlet.Filter; 2 import javax.servlet.FilterConfig; 3 import javax.servlet.ServletRequest; 4 import javax.servlet.ServletResponse; 5 import javax.servlet.FilterChain; 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServletRequest; 8 import java.io.IOException; 9 import java.util.Iterator; 10 import java.util.Set; 11 import java.util.HashSet; 12 // 13 import org.apache.commons.logging.Log; 14 import org.apache.commons.logging.LogFactory; 15 16 /** 17 * This Filter class handle the security of the application. 18 * 19 * It should be configured inside the web.xml. 20 * 21 * @author Derek Y. Shen 22 */ 23 public class SecurityFilter implements Filter { 24 //the login page uri 25 private static final String LOGIN_PAGE_URI = "login.jsf"; 26 27 //the logger object 28 private Log logger = LogFactory.getLog(this.getClass()); 29 30 //a set of restricted resources 31 private Set restrictedResources; 32 33 /** 34 * Initializes the Filter. 35 */ 36 public void init(FilterConfig filterConfig) throws ServletException { 37 this.restrictedResources = new HashSet(); 38 this.restrictedResources.add("/createProduct.jsf"); 39 this.restrictedResources.add("/editProduct.jsf"); 40 this.restrictedResources.add("/productList.jsf"); 41 } 42 43 /** 44 * Standard doFilter object. 45 */ 46 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 47 throws IOException, ServletException { 48 this.logger.debug("doFilter"); 49 50 String contextPath = ((HttpServletRequest)req).getContextPath(); 51 String requestUri = ((HttpServletRequest)req).getRequestURI(); 52 53 this.logger.debug("contextPath = " + contextPath); 54 this.logger.debug("requestUri = " + requestUri); 55 56 if (this.contains(requestUri, contextPath) && !this.authorize((HttpServletRequest)req)) { 57 this.logger.debug("authorization failed"); 58 ((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req, res); 59 } 60 else { 61 this.logger.debug("authorization succeeded"); 62 chain.doFilter(req, res); 63 } 64 } 65 66 public void destroy() {} 67 68 private boolean contains(String value, String contextPath) { 69 Iterator ite = this.restrictedResources.iterator(); 70 71 while (ite.hasNext()) { 72 String restrictedResource = (String)ite.next(); 73 74 if ((contextPath + restrictedResource).equalsIgnoreCase(value)) { 75 return true; 76 } 77 } 78 79 return false; 80 } 81 82 private boolean authorize(HttpServletRequest req) { 83 84 //处理用户登录 85 /* UserBean user = (UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN); 86 87 if (user != null && user.getLoggedIn()) { 88 //user logged in 89 return true; 90 } 91 else { 92 return false; 93 }*/ 94 } 95 }
5、利用Filter限制用户浏览权限
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class RightFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain arg2) throws IOException, ServletException { // 获取uri地址 HttpServletRequest request=(HttpServletRequest)sreq; String uri = request.getRequestURI(); String ctx=request.getContextPath(); uri = uri.substring(ctx.length()); //判断admin级别网页的浏览权限 if(uri.startsWith("/admin")) { if(request.getSession().getAttribute("admin")==null) { request.setAttribute("message","您没有这个权限"); request.getRequestDispatcher("/login.jsp").forward(sreq,sres); return; } } //判断manage级别网页的浏览权限 if(uri.startsWith("/manage")) { //这里省去 } } //下面还可以添加其他的用户权限,省去。 } public void init(FilterConfig arg0) throws ServletException { } }
<!-- 判断页面的访问权限 --> <filter> <filter-name>RightFilter</filter-name> <filter-class>cn.itkui.filter.RightFilter</filter-class> </filter> <filter-mapping> <filter-name>RightFilter</filter-name> <url-pattern>/admin/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>RightFilter</filter-name> <url-pattern>/manage/*</url-pattern> </filter-mapping>
ps:过滤器在web.xml中的配置
<filter> <filter-name>EncodingAndCacheflush</filter-name> <filter-class>EncodingAndCacheflush</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingAndCacheflush</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
六、使用filter生效的注意事项
要传递参数的时候最好使用form进行传参,如果使用链接的话当中文字符的时候过滤器转码是不会起作用的,还有就是页面上
form的method也要设置为post,不然过滤器也起不了作用。