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. json串反转义(消除反斜杠)-- 转载

    JSon串在被串行化后保存在文件中,读取字符串时,是不能直接拿来用JSON.parse()解析为JSON  对象的.因为它是一个字符串,不是一个合法的JSON对象格式.例如下面的JSON串保存在文件中 ...

  2. 20.Scrapy日常练手

    1.创建爬虫项目: scrapy  startproject tutorial 2.创建 spider cd tutorial scrapy  genspider quotes quotes.tosc ...

  3. 3.纯 CSS 创作一个容器厚条纹边框特效

    原文地址:3.纯 CSS 创作一个容器厚条纹边框特效 没有啥好点子呀,不爽 HTML代码: <div class="box"> <div class=" ...

  4. Spring 配置 web.xml (防止spring 内存溢出)

    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" " ...

  5. leetcode933

    public class RecentCounter { Queue<int> Q; public RecentCounter() { Q = new Queue<int>() ...

  6. 解决org.springframework.context.NoSuchMessageException: No message found under code 'login.validate.er

    转自:https://blog.csdn.net/steveguoshao/article/details/36184971 在项目中遇到 org.springframework.context.No ...

  7. jd-eclipse反编译插件的在线安装和使用

    jd-eclipse反编译插件的在线安装和使用 JD-Eclipse是一个Eclipse平台的插件.它允许您调试所有的Java源代码,有了它,以后调试的时候ctrl键就可以一键到底啦.下面简单说说ec ...

  8. 代码报错记录-MAVEN

    报错: COMPILATION ERROR : 程序包不存在. 说是找不到程序包,我的JUNIT是父项目中的,子项目是从JAVA项目转为MAVEN项目的,难道在转成MAVEN项目时对POM文件的修改有 ...

  9. margin和padding的四种写法

    我们经常会看到CSS样式属性中外边距margin和内边距padding的各种用法,这里做一个小结,但只简单介绍margin,因为它们的用法大同小异. 方法一. margin:10px; //4个外边距 ...

  10. Python中的操作符重载

    运算符重载是指在方法中拦截内置的操作----当类的实例出现在内置操作中,Python会自动调用自定义的办法,并且返回自定义方法的操作结果.     类可以重载python的操作符 操作符重载使我们的对 ...