applicationListener和sessionListener使用实例

首先,我们知道web.xml 的加载顺序是:context-param -> listener -> filter -> servlet ,而同个类型之间的实际程序调用的时候的顺序是根据对应的 mapping 的顺序进行调用的。所以没有办法使用注解的方式来获得bean。
这里写了一个applicationListener和sessionListener,代码如下:
applicationListener

package com.service.impl;

import java.util.List;

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

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.pojo.Goods;
import com.pojo.Page;
import com.service.GoodsService;

/**  
* <p>Title: InitConponent.java</p>  
* <p>Description: </p>  
* <p>Copyright: Copyright (c) 2019</p>  
* <p>Company:uestc</p>  
* @author ChenRan  
* @date 2019年1月16日  
* @version 1.0  
*/

@Component
public class InitComponent implements ServletContextListener,ApplicationContextAware
{
	private static ApplicationContext applicationContext;
	
	/**
	 * 服务器启动时被调用的方法
	 * */
	public void contextInitialized(ServletContextEvent sce) 
	{	
		//这里写服务器启动时需要执行的代码
		System.out.println("服务器启动中...");
		ServletContext application = sce.getServletContext();
		GoodsService goodsService = (GoodsService) applicationContext.getBean("goodsServiceImpl");
		
		Page page = new Page();
		//全部商品的计数
		int goodsCount = goodsService.getGoodsCount();
		//计算总页数
		int totalPage = goodsCount%Page.PAGESIZE==0?(goodsCount/Page.PAGESIZE):(goodsCount/Page.PAGESIZE+1);
		page.setTotalPage(totalPage);
		application.setAttribute("page", page);
		//首页的商品信息
		List<Goods> goodsList = goodsService.getGoodsByPage(0, Page.PAGESIZE);
		application.setAttribute("goodsList", goodsList);
		//首页的分类
		List<String> classList = goodsService.getClasses();
		application.setAttribute("classList", classList);
	}
	
	/**
	 * 服务器关闭时被调用
	 * */
	public void contextDestroyed(ServletContextEvent sce) 
	{
		// 这里写服务器关闭时执行的代码
		System.out.println("服务器关闭完成!");
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException 
	{
		this.applicationContext = applicationContext;
	}

}


sessionListener

package com.service.impl;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.stereotype.Component;

import com.pojo.Page;

/**  
* <p>Title: UserSessionListener.java</p>  
* <p>Description: </p>  
* <p>Copyright: Copyright (c) 2019</p>  
* <p>Company:uestc</p>  
* @author ChenRan  
* @date 2019年1月17日  
* @version 1.0  
*/
@Component
public class UserSessionListener implements HttpSessionListener
{	
	/**
	 * 创建该session(用户第一次访问时)执行
	 * */
	public void sessionCreated(HttpSessionEvent se) 
	{	
		//这里写创建session时需要执行的代码
		System.out.println("欢迎访问本网址!"); 
		HttpSession session = se.getSession();
	    ServletContext application = session.getServletContext();
	    Page page = (Page) application.getAttribute("page"); 
	    session.setAttribute("page", page);
	}
	
	/**
	 * 销毁当前session时执行
	 * */
	 public void sessionDestroyed(HttpSessionEvent se) 
	 {	
		 //这里写销毁该session时需要执行的代码,关于session的生命周期的设置可以在web.xml中配置,见web.xml
		 System.out.println("我送你离开,千里之外~");
	 }
}


web.xml添加配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd" 
	version="4.0">
  <display-name>ssm_20190109_shopping</display-name>
  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>
   <!-- Spring配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/spring-*.xml</param-value>
	</context-param>	
	 <!-- Spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>com.service.impl.InitComponent</listener-class>
	</listener>
	
	<listener>
		<listener-class>com.service.impl.UserSessionListener</listener-class>
	</listener>
	
	<session-config><session-timeout>0</session-timeout></session-config>
    	<!-- 配置dispatcher分发器	-->
	<servlet>
	  <servlet-name>dispatcher</servlet-name>
	  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	  <!-- 配置springMVC需要加载的配置文件
	      spring-dao.xml,spring-service.xml,spring-mvc.xml
	      Mybatis - > spring -> springmvc
	   -->
	  <init-param>
	      <param-name>contextConfigLocation</param-name>
	      <param-value>classpath:spring/spring-*.xml</param-value>
	  </init-param>
	  <load-on-startup>1</load-on-startup>
	  <async-supported>true</async-supported>
	</servlet>
	
	<servlet-mapping>
	    <servlet-name>dispatcher</servlet-name>
	    <!-- 默认匹配所有的请求 -->
	    <url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- 配置编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</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>
    </filter>
	<!-- 编码过滤器映射路径 -->
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <!-- /*代表文件夹下的一级文件,/代表文件夹下的全部文件 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  

</web-app>

总结

1.applicationListener是在tomcat服务器启动过程中被调用执行的,sessionListenner是在用户第一次访问时被调用执行的;
2.applicationListener可以用于从数据库中缓存一些对所有的访问者通用的数据,如首页信息,到application中,那么当用户访问的时候就直接从application中取值进行页面渲染,降低了对数据库的访问压力,同时提升了访问速度;
3.sessionListener可以用于对网站访问人数进行统计,也可以用于对存储部分需要一直使用的数据。

后记

新手上路,请多指教!如有错误,恳请各位前辈更正!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值