美文网首页JAVA后台开发_从入门到精通
42 Spring依赖注入servlet会话监听器

42 Spring依赖注入servlet会话监听器

作者: 笑Skr人啊 | 来源:发表于2017-08-29 15:45 被阅读26次

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

1. Spring Beans

创建一个简单的计数服务来打印创建的会话总数。
File : CounterService.java

package com.gp6.common;
 
public class CounterService{
 
    public void printCounter(int count){
        System.out.println("Total session created : " + count);
    }

}

File : counter.xml – Bean配置文件

<?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.gp6.common.CounterService" />
    
</beans>

2. WebApplicationContextUtils

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

package com.gp6.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);
    }
}

3. 集成

唯一的问题是,如何使 Web 应用程序知道在哪里可以加载 Spring bean 配置文件?秘诀是在“web.xml”文件中。
注册“ContextLoaderListener”作为第一个监听器,使Web应用程序知道Spring上下文加载程序。
配置“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.gp6.common.SessionCounterListener
        </listener-class>
  </listener>

  <servlet>
    <servlet-name>Spring DI Servlet Listener</servlet-name>
    <servlet-class>com.gp6.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.gp6.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", "gp6.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应用程序。

代码下载

相关文章

  • 42 Spring依赖注入servlet会话监听器

    Spring提供了一个 “ContextLoaderListener” 监听器,以使 Spring 依赖注入到会话...

  • Spring学习手册(5)—— bean作用域

    Spring学习手册(4)—— Spring 依赖注入中介绍了Spring依赖注入的基本方式以及各种类型的参数注入...

  • Spring学习之依赖注入

    Spring学习之依赖注入 依赖注入的基本概念 依赖注入(Dependecy Injection),也称为IoC(...

  • 2018-05-05

    spring源码分析(三) 目录五、Spring 源码解读--5.4、IOC 容器的依赖注入----1、依赖注入发...

  • spring boot中@WebListener、@WebFil

    在Spring Boot中,当需要以注解的方式添加session监听器或其他servlet(包括监听器、过滤器、以...

  • Spring bean注解

    Spring自带依赖注入注解 @Required,依赖检查 @Autowired,根据Type注入 @Value,...

  • JAVA 核心笔记 || [xxx] Spring 之 依赖注入

    Spring 依赖注入 DL Spring 两种注入方式 Setter 方法注入 构造器注入 使用App.java...

  • 依赖注入

    依赖注入 Spring支持两种依赖注入方式,分别是属性注入和构造函数注入.除此之外,Spring 还支持工厂方法注...

  • spring源码解析-循环依赖

    讲解内容: spring的循环依赖---属性注入--自动注入 spring bean的生命周期 spring be...

  • 依赖注入的方式

    依赖注入: 依赖于某些方式给Bean的资源进行注入 Spring 支持三种依赖注入的方式 属性注入 构造器注入 工...

网友评论

    本文标题:42 Spring依赖注入servlet会话监听器

    本文链接:https://www.haomeiwen.com/subject/mjnodxtx.html