跳转至

过滤器和监听器#

约 401 个字 16 行代码 预计阅读时间 9 分钟

过滤器概述#

过滤器(Filter)是一种用于拦截和处理客户端请求和响应的组件。它们可以在请求到达Servlet之前响应返回客户端之前 ,对请求和响应进行修改或处理。

过滤器入门案例#

  • 编写一个Servlet
Java
package com.luguosong;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author luguosong
 */
@WebServlet("/servlet1")
public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Servlet执行");
    }
}
  • 编写过滤器
Java
package com.luguosong;

import jakarta.servlet.*;

import java.io.IOException;

/**
 * @author luguosong
 */
public class Filter1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("过滤器1请求执行");
        chain.doFilter(request, response);
        System.out.println("过滤器1响应执行");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
  • web.xml中配置过滤器
XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">
    <filter>
        <filter-name>filter1</filter-name>
        <filter-class>com.luguosong.Filter1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter1</filter-name>
        <!--表示过滤所有请求-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>filter2</filter-name>
        <filter-class>com.luguosong.Filter2</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter2</filter-name>
        <!--表示过滤所有请求-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Warning

web.xml中的顺序决定了过滤器的执行顺序。

如果使用的是注解开发,默认执行顺序取决于过滤器类的字母顺序。

执行结果
过滤器1请求执行
过滤器2请求执行
Servlet执行
过滤器2响应执行
过滤器1响应执行

过滤器生命周期#

  • 与Servlet不同,过滤器对象会在服务启动时创建,并执行init()方法。过滤器也是单例的,只会创建一次。
  • 每次客户端请求与过滤器映射的资源时,执行doFilter()方法。
  • 当容器卸载过滤器或者Web应用程序关闭时,容器会调用过滤器的destroy()方法。

监听器概述#

监听器(Listener)是一种特殊的组件,用于监视和响应特定事件或状态变化。它们在Servlet生命周期的不同阶段起作用,通过实现特定的接口来完成其功能。

监听器入门案例#

  • 应用启动和销毁时,监听创建和销毁ServletContext对象:
Java
package com.luguosong;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

/**
 * @author luguosong
 */
public class MyServletContextListener implements ServletContextListener {

    /*
     * ServletContext对象初创建时调用
     * */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContext对象被创建了");
    }

    /*
     * ServletContext对象销毁时调用
     * */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContext对象被销毁了");
    }

}
  • 每次客户端发送http请求,监听ServletRequest对象被创建和销毁:
Java
package com.luguosong;

import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;

/**
 * @author luguosong
 */
public class MyServletRequestListener implements ServletRequestListener {

    /*
     * request对象被创建时调用
     * */
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("request对象被创建了");
    }

    /*
     * request对象被销毁时调用
     * */
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("request对象被销毁");
    }


}
  • 监听session对象被创建和销毁:
Java
package com.luguosong;

import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;

/**
 * @author luguosong
 */
public class MyHttpSessionListener implements HttpSessionListener {
    /*
    * session对象被创建
    * */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session对象被创建");
    }

    /*
    * session对象被销毁
    * */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session对象被销毁");
    }
}
  • 监听request域内容修改:
Java
package com.luguosong;

import jakarta.servlet.ServletRequestAttributeEvent;
import jakarta.servlet.ServletRequestAttributeListener;

/**
 * @author luguosong
 */
public class MyServletRequestAttributeListener implements ServletRequestAttributeListener {
    /*
    * request域中值被创建
    * */
    @Override
    public void attributeAdded(ServletRequestAttributeEvent srae) {
        System.out.println("request域中值被创建");
    }

    /*
    * request域中值被销毁
    * */
    @Override
    public void attributeRemoved(ServletRequestAttributeEvent srae) {
        System.out.println("request域中值被销毁");
    }

    /*
    * request域中值被替换
    * */
    @Override
    public void attributeReplaced(ServletRequestAttributeEvent srae) {
        System.out.println("request域中值被替换");
    }
}
  • 监听Session域内容修改:
Java
package com.luguosong;

import jakarta.servlet.http.HttpSessionAttributeListener;
import jakarta.servlet.http.HttpSessionBindingEvent;

/**
 * @author luguosong
 */
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener {

    /*
     * session域值被添加
     * */
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("session域值被添加");
    }

    /*
     * session域值被删除
     * */
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.out.println("session域值被删除");
    }


    /*
     * session域值被替换
     * */
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        System.out.println("session域值被替换");
    }
}
  • 监听ServletContext域内容修改:
Java
package com.luguosong;

import jakarta.servlet.ServletContextAttributeEvent;
import jakarta.servlet.ServletContextAttributeListener;

/**
 * @author luguosong
 */
public class MyServletContextAttributeListener implements ServletContextAttributeListener {
    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        System.out.println("ServletContext域中值被添加");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
        System.out.println("ServletContext域中值被移除");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        System.out.println("ServletContext域中值被替换");
    }
}
  • 监听指定对象放入Session中:
Java
package com.luguosong;

import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionBindingListener;

/**
 * @author luguosong
 */
public class User implements HttpSessionBindingListener {
    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("User对象被放入到session域中");
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("");
    }

    private String name;
    private Integer age;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • web.xml中配置监听器:
XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">
    <!--配置监听器-->
    <listener>
        <listener-class>com.luguosong.MyServletContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.luguosong.MyServletRequestListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.luguosong.MyHttpSessionListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.luguosong.MyServletRequestAttributeListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.luguosong.MyHttpSessionAttributeListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.luguosong.MyServletContextAttributeListener</listener-class>
    </listener>

</web-app>

评论