Spring提供了一个 “ContextLoaderListener” 监听器,以使 Spring 依赖注入到会话监听器。 在本教程中,通过添加一个 Spring 依赖注入一个bean 到会话监听器修改 HttpSessionListener 例子。

1. Spring Beans

创建一个简单的计数服务来打印创建的会话总数。

File : CounterService.java

package com.yiibai.common;

public class CounterService{

	public void printCounter(int count){
System.out.println("Total session created : " + count);
} }

File : counter.xml – Bean配置文件(注:如果用的是spring注解就不需要这一步了)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="counterService" class="com.yiibai.common.CounterService" /> </beans>

2. WebApplicationContextUtils

使用“WebApplicationContextUtils”来获得 Spring 上下文,以后可以得到任何声明Spring的Bean 在一个正常的 Spring 方式。

File : SessionCounterListener.java

package com.yiibai.common;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; public class SessionCounterListener implements HttpSessionListener { private static int totalActiveSessions; public static int getTotalActiveSession(){
return totalActiveSessions;
} @Override
public void sessionCreated(HttpSessionEvent arg0) {
totalActiveSessions++;
System.out.println("sessionCreated - add one session into counter");
printCounter(arg0);
} @Override
public void sessionDestroyed(HttpSessionEvent arg0) {
totalActiveSessions--;
System.out.println("sessionDestroyed - deduct one session from counter");
printCounter(arg0);
} private void printCounter(HttpSessionEvent sessionEvent){ HttpSession session = sessionEvent.getSession(); ApplicationContext ctx =
WebApplicationContextUtils.
getWebApplicationContext(session.getServletContext()); CounterService counterService =
(CounterService) ctx.getBean("counterService"); counterService.printCounter(totalActiveSessions);
}
}
如果是用的spring注解,并没有手动声明bean的名称,则用CounterService counterService = (CounterService) ctx.getBean("CounterService");来实现

3. 集成

唯一的问题是,如何使 Web 应用程序知道在哪里可以加载 Spring bean 配置文件?秘诀是在“web.xml”文件中。
  1. 注册“ContextLoaderListener”作为第一个监听器,使Web应用程序知道Spring上下文加载程序。
  2. 配置“contextConfigLocation”,并定义Spring的bean配置文件。

File : web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Spring/counter.xml</param-value>
</context-param> <listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener> <listener>
<listener-class>
com.yiibai.common.SessionCounterListener
</listener-class>
</listener> <servlet>
<servlet-name>Spring DI Servlet Listener</servlet-name>
<servlet-class>com.yiibai.common.App</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>Spring DI Servlet Listener</servlet-name>
<url-pattern>/Demo</url-pattern>
</servlet-mapping> </web-app>

File : App.java

package com.yiibai.common;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class App extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException{ HttpSession session = request.getSession(); //sessionCreated() is executed
session.setAttribute("url", "yiibai.com");
session.invalidate(); //sessionDestroyed() is executed PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Spring Dependency Injection into Servlet Listenner</h1>");
out.println("</body>");
out.println("</html>"); }

启动Tomcat,并访问 URL “http://localhost:8080/7.2-SpringDemo/"

输出结果

sessionCreated - add one session into counter
Total session created : 1
sessionDestroyed - deduct one session from counter
Total session created : 0
看看控制台的输出,会得到通过 Spring DI 记数服务的 bean,并打印会话的总数。

总结

在Spring中,“ContextLoaderListener”是一个通用的方法集成Spring依赖注入到几乎所有的Web应用程序。
虽然它的作用在大多数情况下是用来统计在线人数的,但是如果项目有其他需要也可以用它来实现,比如统计用户在线状态等。当然也有可能因为项目框架的原因,无论是登录或者退出(即session销毁)的时候
都会走session创建和销毁的方法,那么就需要你根据相应的情景去处理,来得到你想要的结果了。

Spring依赖注入servlet会话监听器的更多相关文章

  1. java线程中如何使用spring依赖注入

    实现一个线程继承了Thread或实现Runnable接口,想在run方法中使用spring依赖注入(操作数据库),此时报错为空指针,就是说没有注入进来. 实验了几种方式,分别说一下优缺点. 1:写了工 ...

  2. Spring依赖注入(IOC)那些事

    小菜使用Spring有几个月了,但是对于它的内部原理,却是一头雾水,这次借着工作中遇到的一个小问题,来总结一下Spring. Spring依赖注入的思想,就是把对象交由Spring容器管理,使用者只需 ...

  3. Spring依赖注入三种方式详解

    在讲解Spring依赖注入之前的准备工作: 下载包含Spring的工具jar包的压缩包 解压缩下载下来的Spring压缩包文件 解压缩之后我们会看到libs文件夹下有许多jar包,而我们只需要其中的c ...

  4. Spring依赖注入:注解注入总结

    更多11   spring   依赖注入   注解   java 注解注入顾名思义就是通过注解来实现注入,Spring和注入相关的常见注解有Autowired.Resource.Qualifier.S ...

  5. Spring 依赖注入,在Main方法中取得Spring控制的实例

    Spring依赖注入机制,在Main方法中通过读取配置文件,获取Spring注入的bean实例.这种应用在实训的时候,老师曾经说过这种方法,而且学Spring入门的时候都会先学会使用如何在普通的jav ...

  6. Spring依赖注入 --- 简单使用说明

    Spring依赖注入 --- 简单使用说明 本文将对spring依赖注入的使用做简单的说明,enjoy your time! 1.使用Spring提供的依赖注入 对spring依赖注入的实现方法感兴趣 ...

  7. Spring依赖注入 --- 模拟实现

    Spring依赖注入 --- 模拟实现 面向接口编程,又称面向抽象编程, 数据库如果发生更改,对应的数据访问层也应该改变多写几个实现,需要用谁的时候在service里new谁就可以了面向抽象编程的好处 ...

  8. Java Web系列:Spring依赖注入基础

    一.Spring简介 1.Spring简化Java开发 Spring Framework是一个应用框架,框架一般是半成品,我们在框架的基础上可以不用每个项目自己实现架构.基础设施和常用功能性组件,而是 ...

  9. Spring依赖注入的三种方式

    看过几篇关于Spring依赖注入的文章,自己简单总结了一下,大概有三种方式: 1.自动装配 通过配置applicationContext.xml中的标签的default-autowire属性,或者标签 ...

随机推荐

  1. 【Python编程:从入门到实践】chapter3 列表简介

    chapter3 列表简介3.1 列表是什么 列表是一系列按特定顺序排列的元素组成. bicycle = ['trek','cannondale'] print bicycle 3.1.1 访问列表元 ...

  2. 基于Linux的Samba开源共享解决方案测试(一)

    转自http://blog.csdn.net/u013394982/article/details/17914429 Linux操作系统 Linux是一类Unix计算机操作系统的统称.Linux操作系 ...

  3. python学习笔记一和PHP的一些对比

    python和php一样是 解释性语言 php和php一样 定义变量不需要指定类型,C语言中的print函数 在python中也是适用的 python编码 适用缩进  4个空格,通常存储为UTF-8模 ...

  4. 33. Linux安装配置JDK-7

    安装说明 系统环境:centos-6.3安装方式:rpm安装 软件:jdk-7-linux-x64.rpm下载地址:http://www.oracle.com/technetwork/java/jav ...

  5. Django中使用Celery实现定时任务(用djcelery)

    一.引言 Django是python语言下的一个比较热门的Web框架,越来越多的企业和开发者使用Django实现自己的Web服务器.在Web服务器开发过程中,有时候我们不仅仅是要实现Web服务器端和用 ...

  6. jQuery上传插件uploadify 3.2.1

    1.属性 名称 默认值 说明 swf   [必须设置]swf的路径 uploader   [必须设置]服务器端脚本文件路径 uploadLimit 999 最多上传文件数量 checkExisting ...

  7. WDA-文档-基础篇/进阶篇/讨论篇

    本文介绍SAP官方Dynpro开发文档NET310,以及资深开发顾问编写的完整教程.   链接:http://pan.baidu.com/s/1eR9axpg 密码:kf5m NET310 ABAP ...

  8. Git revert merge

    从history1分出来的A, B两个branch A上有一些更改,例如 changeA2 changeA1 history1 B上有一些更改,例如 changeB2 changeB1 history ...

  9. centos6.8 安装python2.7 or python3.6

    from:https://danieleriksson.net/2017/02/08/how-to-install-latest-python-on-centos/ 准备 # Start by mak ...

  10. X86汇编概要

    来自:https://www.cnblogs.com/jiftle/p/8453106.html 本文翻译自:http://www.cs.virginia.edu/~evans/cs216/guide ...