Day_09 Filter和监听器

2022/3/21 23:28:23

本文主要是介绍Day_09 Filter和监听器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文章目录

      • 01-Filter概述(掌握)
      • 02-Filter入门案例(掌握)
      • 03-Filter执行流程(掌握)
      • 04-Filter生命周期(掌握)
      • 05-Filter相关配置(掌握)
      • 06-过滤器链(掌握)
      • 07-Filter拦截行为(掌握)
      • 08-Filter注解开发(掌握)
      • 09-监听器概述(掌握)
      • 10-一类监听器概述(掌握)
      • 11-一类监听器之ServletRequestListener(掌握)
      • 12-一类监听器之ServletContextListener(重点)
      • 13-二类监听器概述(掌握)
      • 14-二类监听器之ServletRequestAttributeListener(了解)
      • 15-三类监听器概述(了解)
      • 16-三类监听器之HttpSessionBindingListener(掌握)
      • 17-session钝化和活化(掌握)
      • 18-三类监听器之HttpSessionActivationListener(掌握)
      • 19-监听器的注解开发(掌握)

01-Filter概述(掌握)

  • 概述

    A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. 
    
    Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, and a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks. 
    
    Examples that have been identified for this design are: 
        Authentication Filters 
        Logging and Auditing Filters 
        Image conversion Filters 
        Data compression Filters 
        Encryption Filters 
        Tokenizing Filters 
        Filters that trigger resource access events 
        XSL/T filters 
        Mime-type chain Filter 
    
    • Filter对象可以用于过滤request和response;
    • Filter对象有一个FilterConfig对象,通过这个对象可以获取初始化参数,以及使用ServletContext对象;
    • 适用场景:Authentication Filters 、 Tokenizing Filters …

02-Filter入门案例(掌握)

  • 开发步骤

    • ①定义FIlter类实现Filter接口
      • 重写方法
    • ②编写web.xml
      • 声明Filter类
  • ①定义FIlter类实现Filter接口

    @WebServlet("/demo01")
    public class Demo01Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("Demo01Servlet");
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
  • ②编写web.xml

    <filter>
        <filter-name>Demo01Filter</filter-name>
        <filter-class>com.atguigu.filter.Demo01Filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Demo01Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

03-Filter执行流程(掌握)

  • 执行流程
    • image-20220316093744782
  • 注意事项
    • chain.doFilter只能执行一次。

04-Filter生命周期(掌握)

  • 生命周期
    • 实例化
      • 服务器启动
    • 初始化
      • 服务器启动
    • 销毁
      • 服务器关闭

05-Filter相关配置(掌握)

  • 相关配置

    • ①初始化参数
    • ②过滤路径
      • 2.1,完全匹配:以"/"开头
      • 2.2,目录匹配:以"/“开头,以”*"结尾
      • 2.3,后缀名匹配: 以"*"开头,以"后缀名"结尾
      • 2.4,过滤指定Servlet
  • ①初始化参数

    <filter>
        <filter-name>Demo03Filter</filter-name>
        <filter-class>com.atguigu.filter.Demo03Filter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Demo03Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    public class Demo03Filter implements Filter {
    
        private String encoding;
    
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            encoding = filterConfig.getInitParameter("encoding");
            System.out.println("encoding = " + encoding);
    
            Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();
            while (initParameterNames.hasMoreElements()) {
                String initParameterName = initParameterNames.nextElement();
                String initParameterValue = filterConfig.getInitParameter(initParameterName);
                System.out.println("initParameterName = " + initParameterName + " , initParameterValue = " + initParameterValue);
    
            }
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
            System.out.println("encoding = " + encoding);
            chain.doFilter(request, response);//相当于执行Demo01Servlet
    
        }
    }
    
  • ②过滤路径

    <filter>
        <filter-name>Demo04Filter</filter-name>
        <filter-class>com.atguigu.filter.Demo04Filter</filter-class>
    </filter>
    
    <!--2.1,完全匹配:以"/"开头-->
    <!--
    <filter-mapping>
        <filter-name>Demo04Filter</filter-name>
        <url-pattern>/demo01</url-pattern>
    </filter-mapping>
    -->
    <!--2.2,目录匹配:以"/"开头,以"*"结尾-->
    <!--
    <filter-mapping>
        <filter-name>Demo04Filter</filter-name>
        <url-pattern>/a/b/c/*</url-pattern>
    </filter-mapping>
    -->
    <!--2.3,后缀名匹配: 以"*"开头,以"后缀名"结尾-->
    <!--
    <filter-mapping>
        <filter-name>Demo04Filter</filter-name>
        <url-pattern>*.html</url-pattern>
    </filter-mapping>
    -->
    <!--2.4,过滤指定Servlet-->
    <filter-mapping>
        <filter-name>Demo04Filter</filter-name>
        <servlet-name>Demo01Servlet</servlet-name>
        <servlet-name>Demo02Servlet</servlet-name>
    </filter-mapping>
    

06-过滤器链(掌握)

  • 概述

    • 由多个过滤器组成一个过滤链。
    • 只有当所有过滤器都放行,请求才能到达目标资源,如果有某一 个过滤器没有放行,那么请求则无法到达后续过滤器以及目标资源
  • 执行顺序

    • 先配置,先过滤,后放行.
  • 原因分析

    • image-20220316103506951
  • 代码实现

    public class Demo05Filter implements Filter {
    
    
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            System.out.println("Demo05Filter 过滤");
            chain.doFilter(request, response);//相当于执行Demo01Servlet
            System.out.println("Demo05Filter 放行");
    
        }
    }
    
    public class Demo06Filter implements Filter {
    
    
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            System.out.println("Demo06Filter 过滤");
            chain.doFilter(request, response);//相当于执行Demo01Servlet
            System.out.println("Demo06Filter 放行");
    
        }
    }
    
    <filter>
        <filter-name>Demo05Filter</filter-name>
        <filter-class>com.atguigu.filter.Demo05Filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Demo05Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>Demo06Filter</filter-name>
        <filter-class>com.atguigu.filter.Demo06Filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Demo06Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

07-Filter拦截行为(掌握)

  • 概述

    • Filter过滤器默认拦截的是请求,但是在实际开发中,我们还有请求转发和请求包含,以及由服务器触 发调用的全局错误页面。默认情况下过滤器是不参与过滤的,要想使用,就需要我们配置。
  • 拦截行为

    • ①REQUEST : 默认值,过滤请求
    • ②ERROR : 过滤跳转全局错误页面
    • ③FORWARD :过滤请求转发
    • ④INCLUDE : 过滤请求包含
  • ①REQUEST : 默认值,过滤请求

    <!--①REQUEST : 默认值,过滤请求-->
    <filter-mapping>
        <filter-name>Demo07Filter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
    
  • ②ERROR : 过滤跳转全局错误页面

    <!--②ERROR : 过滤跳转全局错误页面-->
    <filter-mapping>
        <filter-name>Demo07Filter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>
    
  • ③FORWARD :过滤请求转发

    <!--③FORWARD :过滤请求转发-->
    <filter-mapping>
        <filter-name>Demo07Filter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    
  • ④INCLUDE : 过滤请求包含

    <!--④INCLUDE : 过滤请求包含-->
    <filter-mapping>
        <filter-name>Demo07Filter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>
    

08-Filter注解开发(掌握)

  • 概述

    • 使用@WebFilter注解替代XML配置。
  • 源码

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface WebFilter {
    
        WebInitParam[] initParams() default {};
    
        String filterName() default "";
    
        String[] servletNames() default {};
    
        String[] value() default {};
    
        String[] urlPatterns() default {};
    
        DispatcherType[] dispatcherTypes() default {DispatcherType.REQUEST};
    
    }
    
  • 代码实现1

    @WebFilter(
            filterName = "Demo08Filter",
            urlPatterns = {
                    "/demo01", "/demo02"
            },
            initParams = {
                    @WebInitParam(
                            name = "encoding", value = "utf-8"
                    ),
                    @WebInitParam(
                            name = "encoding2", value = "gbk"
                    )
            },
            dispatcherTypes = {
                    DispatcherType.REQUEST,
                    DispatcherType.FORWARD,
                    DispatcherType.INCLUDE,
                    DispatcherType.ERROR
            },
            servletNames = {
                    "Demo01Servlet", "Demo02Servlet"
            }
    
    )
    public class Demo08Filter implements Filter {
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            System.out.println("Demo08Filter 过滤");
            chain.doFilter(request, response);//相当于执行Demo01Servlet
            System.out.println("Demo08Filter 放行");
    
        }
    }
    
  • 代码实现2

    @WebFilter("/*")
    public class Demo09Filter implements Filter {
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            System.out.println("Demo09Filter 过滤");
            chain.doFilter(request, response);//相当于执行Demo01Servlet
            System.out.println("Demo09Filter 放行");
    
        }
    }
    

09-监听器概述(掌握)

  • 回顾
    • 事件源 : 事件发生的源头
    • 监听器 : 监听事件发生的组件
    • 事件绑定 : 将事件源和监听器关联起来
    • 事件 : 一件事
  • Servlet事件
    • 事件源 : 三大域对象
    • 监听器 : 三类监听器
    • 事件绑定 : xml配置、注解配置
    • 事件 : 三大域对象内容发生改变
  • 分类
    • 一类监听器
      • 监听三大域对象的状态改变(初始化、销毁)
    • 二类监听器
      • 监听三大域对象中的内容改变(添加、修改、移除)
    • 三类监听器
      • 监听三大域对象中的对象状态改变(绑定/解绑、钝化/活化)

10-一类监听器概述(掌握)

  • 概述
    • 监听三大域对象的状态改变(初始化、销毁)
  • 一类监听器
    • ServletRequestListener
      • 监听ServletRequest域对象的状态改变(初始化、销毁)
    • HttpSessionListener
      • 监听HttpSession域对象的状态改变(初始化、销毁)
    • ServletContextListener
      • 监听ServletContext域对象的状态改变(初始化、销毁)

11-一类监听器之ServletRequestListener(掌握)

  • 概述

    • 监听ServletRequest域对象的状态改变(初始化、销毁)
  • 代码实现

    public class MyServletRequestListener implements ServletRequestListener {
    
        @Override
        public void requestInitialized(ServletRequestEvent sre) {
            System.out.println("requestInitialized");
        }
    
        @Override
        public void requestDestroyed(ServletRequestEvent sre) {
            System.out.println("requestDestroyed");
        }
    
    
    }
    
    <listener>
        <listener-class>com.atguigu.listener1.MyServletRequestListener</listener-class>
    </listener>
    

12-一类监听器之ServletContextListener(重点)

  • 概述

    • 监听ServletContext域对象的状态改变(初始化、销毁)
  • 代码实现

    public class MyServletContextListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            System.out.println("contextInitialized");
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            System.out.println("contextDestroyed");
    
        }
    }
    
    <listener>
        <listener-class>com.atguigu.listener1.MyServletContextListener</listener-class>
    </listener>
    

13-二类监听器概述(掌握)

  • 概述
    • 监听三大域对象中的内容改变(添加、修改、移除)
  • 分类
    • ServletRequestAttributeListener
      • 监听ServletRequest域对象中的内容改变(添加、修改、移除)
    • HttpSessionAttributeListener
      • 监听HttpSession域对象中的内容改变(添加、修改、移除)
    • ServletContextAttributeListener
      • 监听ServletContext域对象中的内容改变(添加、修改、移除)

14-二类监听器之ServletRequestAttributeListener(了解)

  • 概述

    • 监听ServletRequest域对象中的内容改变(添加、修改、移除)
  • 代码实现

    public class MyServletRequestAttributeListener implements ServletRequestAttributeListener {
    
        @Override
        public void attributeAdded(ServletRequestAttributeEvent srae) {
            System.out.println("attributeAdded");
        }
    
        @Override
        public void attributeRemoved(ServletRequestAttributeEvent srae) {
            System.out.println("attributeRemoved");
    
        }
    
        @Override
        public void attributeReplaced(ServletRequestAttributeEvent srae) {
            System.out.println("attributeReplaced");
    
        }
    }
    
    <listener>
        <listener-class>com.atguigu.listener2.MyServletRequestAttributeListener</listener-class>
    </listener>
    

15-三类监听器概述(了解)

  • 概述
    • 监听三大域对象中的对象状态改变(绑定/解绑、钝化/活化)
  • 分类
    • HttpSessionBindingListener
      • 监听HttpSession域对象中的对象状态改变(绑定/解绑)
    • HttpSessionActivationListener
      • 监听HttpSession域对象中的对象状态改变(钝化/活化)

16-三类监听器之HttpSessionBindingListener(掌握)

  • 概述

    • 监听HttpSession域对象中的对象状态改变(绑定/解绑)
  • 代码实现

    public class Student  implements HttpSessionBindingListener {
    
        private Integer studentId;
        private String studentName;
    
        @Override
        public void valueBound(HttpSessionBindingEvent event) {
            System.out.println("Student绑定");
        }
    
        @Override
        public void valueUnbound(HttpSessionBindingEvent event) {
            System.out.println("Student解绑");
        }
    
    }
    

17-session钝化和活化(掌握)

  • 概述

    • 当服务器突然宕机时,有一些需要长期使用的session数据会销毁,重启服务器后无法使用这些数据;
    • 因此,我们需要将这些session数据保留,并且下次重启之后可以使用。此时就可以考虑session的钝 化与活化
  • 钝化

    • 序列化 : 当服务器关闭时,将session中的对象信息以字节的形式存储到缓存文件
  • 活化

    • 反序列化 : 当服务器启动时,将缓存文件中的字节数据以对象的形式还原到session中
  • 开发步骤

    • ①JavaBean实体类实现Serializable接口
    • ②编写tomcat的context.xml文件
  • ①JavaBean实体类实现Serializable接口

    public class Teacher implements Serializable {
    
        private String teacherName;
    
    }
    
  • ②编写tomcat的context.xml文件

    <Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="true" maxIdleSwap="1">
        <Store className="org.apache.catalina.session.FileStore" directory="E:\Program Files\apache-tomcat-9.0.56\conf\Session"/>
    </Manager>
    

18-三类监听器之HttpSessionActivationListener(掌握)

  • 概述

    • 监听HttpSession域对象中的对象状态改变(钝化/活化)
  • 代码实现

    public class Teacher implements Serializable , HttpSessionActivationListener {
    
        private String teacherName;
    
        @Override
        public void sessionWillPassivate(HttpSessionEvent se) {
            System.out.println("Teacher钝化");
        }
    
        @Override
        public void sessionDidActivate(HttpSessionEvent se) {
            System.out.println("Teacher活化");
    
        }
    }
    

19-监听器的注解开发(掌握)

  • 概述

    • 使用@WebListener注解替代XML配置.
  • 代码实现

    @WebListener
    public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener {
    
        @Override
        public void attributeAdded(HttpSessionBindingEvent se) {
            System.out.println("attributeAdded");
        }
    
        @Override
        public void attributeRemoved(HttpSessionBindingEvent se) {
            System.out.println("attributeRemoved");
    
        }
    
        @Override
        public void attributeReplaced(HttpSessionBindingEvent se) {
            System.out.println("attributeReplaced");
    
        }
    }
    


这篇关于Day_09 Filter和监听器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程