过滤器和监听器
1.作用
- 过滤器:过滤指定的请求并对响应进行统一的处理
- 监听器:根据实现的接口不同可实现对不同对象的监听和创建
2.实现及创建时机
- 过滤器:实现Filter接口 并实现 init() doFilter() destory()方法,随着web容器的创建而创建 在访问指定请求时发挥作用,随着容器的关闭而销毁。
- 监听器:可实现 HttpSessionListener 等不同对象的接口,实现对应的create 和destory方法。
3.代码
- 过滤器:
public class FilterTest implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("过滤器已经初始化"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); System.out.println("请求要进入chain链"); //调用该方法保证请求到这里可以继续往下请求 chain.doFilter(request,response); System.out.println("请求离开chain链"); } @Override public void destroy() { System.out.println("过滤器已经销毁"); } }
xml配置: 在filter-mapping标签中也可根据servletname来进行过滤
<filter> <filter-name>encoding</filter-name> <filter-class>com.test.filter.FilterTest</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
- 监听器
public class TestListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent se) { Integer count = (Integer)se.getSession().getServletContext().getAttribute("number"); System.out.println("count:" + count); if (null == count ){ se.getSession().getServletContext().setAttribute("number",1); } else { se.getSession().getServletContext().setAttribute("number" ,count + 1); } } @Override public void sessionDestroyed(HttpSessionEvent se) { } }
xml配置:
<listener> <listener-class>com.test.study.TestListener</listener-class> </listener>