【java web】监听器listener

akcsdno 2020-01-04

一、简介

Java的监听器,也是系统级别的监听。监听器随web应用的启动而启动。Java的监听器在c/s模式里面经常用到,它会对特定的事件产生产生一个处理。监听在很多模式下用到,比如说观察者模式,就是一个使用监听器来实现的,在比如统计网站的在线人数。

1.1 监听器分类

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

ServletContext对象监听器
  HttpSession对象监听器
  ServletRequest对象监听器

2)按监听的事件划分

对象自身的创建和销毁的监听器
  对象中属性的创建和消除的监听器
  session中的某个对象的状态变化的监听器

二、适用场景

springMVC监听器主要的作用就是spring容器启动的时候加载一些数据,最常用的功能就是开发权限系统的时候,当监听器启动的时候,从数据库加载权限url。

三、实现

一、ContextLoaderListener

ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,web.xml配置这个监听器启动容器时,就会默认执行它实现的方法。在ContextLoader-Listener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。ContextLoader可以由 ContextLoaderListener和ContextLoaderServlet生成。查看ContextLoaderServlet的API,它也关联了ContextLoader这个类而且它实现了HttpServlet这个接口;ContextLoader创建的是XmlWebApplicationContext这样一个类,实现的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext->BeanFactory。这样一来spring中的所有bean都由这个类来创建。如果在web.xml中不写任何参数配置信息,默认的路径是/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml;如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:

<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>  
        /WEB-INF/classes/applicationContext-*.xml   
    </param-value>
</context-param>

  在<param-value></param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并一“,”号分隔。上面的applicationContext-*.xml采用通配符,比如这那个目录下有applicationContext-ibatis-base.xml,applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。由此可见applicationContext.xml的文件位置就可以有两种默认实现:第一种:直接将之放到/WEB-INF下,之后在web.xml中声明一个listener;第二种:将之放到classpath下,但是此时要在web.xml中加入<context-param>,用它来指明你的applicationContext.xml的位置以供web容器来加载。按照Struts2 整合spring的官方给出的档案,写成:

<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> 
</context-param>

自定义监听器的配置

1配置自定义的监听器需要配置spring容器监听器,因为自定期监听器需要从spring容器中拿取数据,并且自定义监听器的配置文件位于spring监听器之后

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">



    <display-name>Device Manage Web Application</display-name>

    <!-- 获取登陆者信息 -->
    <filter>
        <filter-name>testFilter</filter-name>
        <filter-class>com.my.dm.filter.TestFilter</filter-class>
    
        <init-param>
            <param-name>demo</param-name>
            <param-value>112.2.36</param-value>
        </init-param>
        </filter>
    <filter-mapping>
        <filter-name>testFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 统一编码 解决中文乱码问题 -->
    <filter>
        <filter-name>charsetEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>charsetEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- DispatcherServlet -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-mvc.xml</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--3. Load Spring Config File -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/beans.xml</param-value>
    </context-param>    
    
    <!-- 4.spring listener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <!--5.spring 防内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>    

    <!-- 6.common Page! -->
    <welcome-file-list>
        <welcome-file>/welcome.jsp</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/error/404.jsp</location>
    </error-page>
    
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/error/500.jsp</location>
    </error-page>    
    
    <!-- 自定义监听器 -->
    <listener>
        <listener-class>com.my.dm.listener.TestListener</listener-class>
    </listener>    

</web-app>

2,springMC自定义监听器需要实现ServletContextListener接口

package com.my.dm.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.my.dm.service.DeviceService;

public class TestListener implements ServletContextListener {
    private Logger logger = LogManager.getLogger(TestListener.class);

    /**
     * 当容器启动完成之后
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // TODO Auto-generated method stub
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());

        DeviceService deviceService = ac.getBean(DeviceService.class);
        logger.error("This is test for TestListener!");
        logger.error(deviceService.getDeviceByNameIp("", "4.154.135.74").get(0));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub

    }

}

参考:

https://www.jianshu.com/p/82ae825b849b

https://www.cnblogs.com/lukelook/p/11079113.html#t2

相关推荐

TesterJingel / 0评论 2013-08-27

eastnow / 0评论 2013-01-15