java---过滤器、监听器

一、过滤器(Filter)

  1、过滤器作用

    能够对目标资源的请求和响应进行过滤或拦截,主要功能是登录验证、编码处理

    javaWeb三大组件:servelt、Filter、Listener(监听器)

  2、使用入门

    ①创建类实现Filter接口     ②重写接口中的方法   ③配置需要过滤的路径  ④在doFilter中写逻辑判断,使用filterChain对符合条件的放行

@WebFilter("/*")   //使用注解配置需要过滤的路径
public class FilterDemo2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入过滤器了");
        filterChain.doFilter(servletRequest,servletResponse);//对请求或响应放行
    }

    @Override
    public void destroy() {

    }
}

    使用配置文件配置需要过滤的路径: web.xml

   <filter>
        <filter-name>filterDemo2</filter-name>
        <filter-class>com.fy.danbiao.Filter.FilterDemo2</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filterDemo2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  3、过滤器的细节

    ①过滤器的运行流程

      资源请求----》过滤器-----》放行-----》资源-----》响应-----》过滤器-----》客户端

    ②生命周期

      和servlet相似:

      init():初始化

      doFilter():放行方法

      destory():销毁

    ③过滤器配置

      访问路径配置:

        过滤所有路径:/*

        过滤指定目录的路径:/user/*

        过滤指定结尾符:.jsp、.do

        过滤具体的资源路径:index.jsp

      访问的请求类型设置:dispatherTypes属性,默认是request

        request:请求类型,默认值

        forward:转发访问资源

        include:包含访问资源

        error:错误跳转资源

        async:异步访问资源

        配置方式:①注解:@WebFilter(value = "/*",dispatcherTypes = DispatcherType.INCLUDE)

             ②配置文件:

<filter>
        <filter-name>filterDemo2</filter-name>
        <filter-class>com.fy.danbiao.Filter.FilterDemo2</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filterDemo2</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>

      ④过滤器链的执行(当项目中有多个过滤器时)

        客户端请求---》过滤器1---》过滤器2---》资源执行---》过滤器2---》过滤器1

        如何判断那个过滤器先执行?两种方式

           ①web.xml中配置的过滤器,那个先配置,那个先执行。

           ②根据过滤器类名来比较,类名的每个字符一次比较码值,小的先执行

   4、过滤器案例:判断访问者是否登录,如果登录,就放行,没有登录,跳转到登录页面

@WebFilter("/*")
public class FilterDemo implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    /*实现:
     *1、判断用户是否登录,如果没有登录,就跳转倒login.jsp页面,如果登陆了,跳转到index.jsp
     *2、设置请求和相应的编码
     * */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
//        1、设置编码格式
      req.setCharacterEncoding("utf-8");
      resp.setContentType("text/html;charset=utf-8");
//      2、过滤请求
        String requestURI = req.getRequestURI();//获取访问的路径
//         有些路径不用拦截,就直接放行了   目前包括跳转到 登录页面/登录请求/静态资源
        if(requestURI.contains("login.jsp") || requestURI.contains("login") ||requestURI.contains("lay")){
            filterChain.doFilter(req,resp);
        }else {
//            获取session对象
            HttpSession session = req.getSession();
//            得到session对象中的值
            Object t_staff = session.getAttribute("t_staff");
            System.out.println("t_staff"+t_staff);
            if(t_staff!=null){
                filterChain.doFilter(req,resp);
            }else {
                resp.sendRedirect("/layui/login.jsp");
            }
        }


    }

    @Override
    public void destroy() {

    }
}
View Code

二、监听器(Listener)

  1、作用:监听web应用,监听很多信息的初始化、销毁,属性的添加、移除、修改

  2、监听器的分类

    一个web应用程序的整个运行周期中,会创建和销毁三个重要的对象:

        ServletContext、HttpSession、ServletRequest

    按监听的对象,可划分为:

        ServletContext对象监听器:ServletContextListener、ServletContextAttributeListener

        HttpSession对象监听器:HttpSessionListener、HttpSessionAttributeListener

        ServletRequest对象监听器:ServletRequestListener、ServletRequestAttributeListener

    按监听事件的划分:

        对象的创建和销毁的监听

        对象中属性的添加、修改、移除的监听

        session中某个对象的状态变化的监听器

  3、使用

    ①实现指定监听器的接口

       ②重写方法

    以HttpSessionListener举例:

@WebListener //配置监听器
public class ListenerDemo2 implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session创建");
    }
    
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session销毁");
    }
}

  使用web.xml配置文件来配置监听器:

  <listener>
    <listener-class>com.fy.danbiao.listener.ListenerDemo2</listener-class>
  </listener>

 4、监听系统的在线人数(使用ServletContextListener、HttpSessionListener) 

@WebListener
public class ListenerDemo implements ServletContextListener,HttpSessionListener {
    ServletContext application;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
//        获取上下文对象
        application = servletContextEvent.getServletContext();
//         是否有计数器
        if(application.getAttribute("count")==null){
//            存进去,只执行一次
            application.setAttribute("count",0);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
//        获取先前的在线人数,为什么要把在线人数放在ServletContext,因为再HttpSession中只能存在30分钟
        int count = Integer.parseInt(application.getAttribute("count").toString());
        count++;
        application.setAttribute("count",count);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        Integer count=Integer.valueOf(application.getAttribute("count").toString());
        count--;
        System.out.println(count);
        application.setAttribute("count",count);
    }
}

    

        

原文地址:https://www.cnblogs.com/fbbg/p/14265485.html