过滤器和监听器

  • 2019-12-10
  • 201
  • 0

过滤器

Servlet的作用是针对浏览器发起的请求,进行请求的处理,通过Servlet技术我们可以灵活的进行请求的处理,但是我们不但要对请求处理,还需对服务器的资源进行统一的管理,比如请求编码格式的统一设置,资源的统一分配等。这就需要使用过滤器对服务器资源进行管理。使用方式:

  • 创建一个实现Filter接口的普通java类
  • 覆写接口的方法,init,doFilter,destory

执行流程:

浏览器发送请求到服务器,服务器接收到请求后,根据URI信息在web.xml找到对应的过滤器执行doFilter方法,该方法对此次请求进行处理如果符合要求则放行,放心后如果还有符合要求的过滤器则继续执行过滤,然后找到对应的servlet进行处理,servlet处理完毕后,仍然需要继续返回相应的doFilter的方法继续执行后再返回。

package com.husaky.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化了"); // 服务器启动
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行了");
        // 设置编码格式
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        // 判断session,防止session失效后继续生成session 数据丢失
        HttpSession hs = ((HttpServletRequest)servletRequest).getSession();
        if (hs.getAttribute("user") == null) {
            ((HttpServletResponse)servletResponse).sendRedirect("/a/login.jsp");
        }else {
            // 符合该过滤器规则 必须手动放行
            filterChain.doFilter(servletRequest,servletResponse); //继续下一个过滤器
        }
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁了");// 服务器关闭
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!-- 配置过滤器 -->
    <filter>
        <filter-name>myFilter</filter-name>
        <filter-class>com.husaky.filter.MyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>myFilter</filter-name>
        <url-pattern>/*</url-pattern> <!--/*表示所有请求都要走这个过滤器,通常公共过滤放这里 -->
    </filter-mapping>

    <filter>
        <filter-name>myFilter2</filter-name>
        <filter-class>com.husaky.filter.MyFilter2</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>myFilter2</filter-name>
        <url-pattern>/*.do</url-pattern> <!--表示url为.do结尾的执行这个过滤,模块过滤 -->
    </filter-mapping>
    <!--/aa url匹配aa执行这个过滤器 /ts.do 同理 -->

    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>com.husaky.filter.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/ts</url-pattern>
    </servlet-mapping>

</web-app>

过滤器

在Servlet技术中,request,session,application作用域对象,主要作用是实现数据在不同场景中的灵活转换,但是数据的具体流转过程我们看不见,比如作用域对象是什么时候创建和销毁的,数据是什么时候存取的、改变和删除的,因为具体的流转过程看不到,所以也就无法再指定的时机对数据和对象进行操作,比如session销毁的时候,在线人数-1.

Servlet监听器是Servlet规范中定义的一种特殊类,用于监听ServletContext,HttpSession和ServletRequest扥域对象的创建和销毁事件,以及监听这些域对象中属性发生修改的事件,在事件发生之前,之后进行一些处理,比如统计在线人数。

package com.husaky.listener;

import javax.servlet.*;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MyListener implements ServletRequestListener,
        ServletRequestAttributeListener, HttpSessionListener,
        HttpSessionAttributeListener,
        ServletContextListener,
        ServletContextAttributeListener {

    // request 对象销毁
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        System.out.println("我被销毁了");
    }

    // request对象创建
    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
//        servletRequestEvent.getServletContext()
        System.out.println("我被创建了");
    }

    // 监听request作用域数据的添加
    @Override
    public void attributeAdded(ServletRequestAttributeEvent servletRequestAttributeEvent) {
        System.out.println("request中添加了一个属性(数据)"+servletRequestAttributeEvent.getName()
        +":"+servletRequestAttributeEvent.getValue());
    }

    // 监听request作用域数据的删除
    @Override
    public void attributeRemoved(ServletRequestAttributeEvent servletRequestAttributeEvent) {

    }

    //
    @Override
    public void attributeReplaced(ServletRequestAttributeEvent servletRequestAttributeEvent) {

    }

    // session创建
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        // 获取servletContext对象
        ServletContext sc = httpSessionEvent.getSession().getServletContext();
        // 获取在线人数
        int count = (int)sc.getAttribute("COUNT");
        sc.setAttribute("COUNT", ++count);
        System.out.println("session创建了");
    }

    // session销毁
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        // 获取servletContext对象
        ServletContext sc = httpSessionEvent.getSession().getServletContext();
        // 获取在线人数
        int count = (int)sc.getAttribute("COUNT");
        sc.setAttribute("COUNT", --count);
        System.out.println("session创建了");
        System.out.println("session销毁了");
    }

    // session属性添加
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("session中添加了一个属性(数据)"+httpSessionBindingEvent.getName()
                +":"+httpSessionBindingEvent.getValue());
    }

    // session属性删除
    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    // session属性修改
    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    // application对象初始化
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext  sc = servletContextEvent.getServletContext();
        //在application对象存储变量来统计在线人数
        sc.setAttribute("COUNT", 0);
        System.out.println("服务器启动application对象创建了");
    }

    // application对象销毁
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("服务器关闭application对象销毁了");

    }

    //application对象添加数据
    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {

    }

    //application对象删除数据
    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {

    }

    // application对象修改数据
    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {

    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!-- 配置过滤器 -->
    <filter>
        <filter-name>myFilter</filter-name>
        <filter-class>com.husaky.listener.MyListener</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>myFilter</filter-name>
        <url-pattern>/*</url-pattern> <!--/*表示所有请求都要走这个过滤器,通常公共过滤放这里 -->
    </filter-mapping>

    <filter>
        <filter-name>myFilter2</filter-name>
        <filter-class>com.husaky.listener.MyFilter2</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>myFilter2</filter-name>
        <url-pattern>/*.do</url-pattern> <!--表示url为.do结尾的执行这个过滤,模块过滤 -->
    </filter-mapping>
    <!--/aa url匹配aa执行这个过滤器 /ts.do 同理 -->

    <!-- 配置监听器 -->
    <listener>
        <listener-class>com.husaky.listener.MyListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>com.husaky.listener.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/ts</url-pattern>
    </servlet-mapping>

</web-app>
package com.husaky.listener;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("str", "监听器");
        resp.getWriter().write("this is listener");
        HttpSession hs = req.getSession();
        hs.setAttribute("str", "session add data");
        hs.invalidate();// 立马销毁session
    }
}

评论

还没有任何评论,你来说两句吧

粤ICP备17155863号

- 友情链接 - Theme by Qzhai