Session监听器在项目中的使用

session监听器可以用来统计用户在线时长,统计网站的访问人数,以及在线用户。除了session监听器,还有websocket也可以实现这些功能。

我在项目中使用session监听器是用于统计用户在线时长。

1、首先创建MySessionListener并让它实现HttpSessionListener, ServletContextListener接口

实现ServletContextListener接口,是因为监听器中无法自动注入service,ServletContextListener的contextInitialized(ServletContextEvent  sce)方法,可以帮助我们注入spring容器一个bean。 

package com.test.platform.web.util.authorization;

import com.test.platform.core.system.service.CustomerUserLoginLogService;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
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;

/**
 * Session监听器 
 * Created by Administrator on 2018/9/28.
 */
public class MySessionListener implements HttpSessionListener, ServletContextListener {

  private CustomerUserLoginLogService customerUserLoginLogService;

  @Override
  public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    //此方法在Session创建时执行
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent event) {
     //此方法在Session销毁时执行
  }

  @Override
  public void contextInitialized(ServletContextEvent sce) {
     //此方法可注入service层和dao层
    ApplicationContext ac = WebApplicationContextUtils
        .getWebApplicationContext(sce.getServletContext());
    customerUserLoginLogService = (CustomerUserLoginLogService) ac
        .getBean("customerUserLoginLogService");
  }

  @Override
  public void contextDestroyed(ServletContextEvent servletContextEvent) {

  }
}

在sessionCreated和sessionDestoryed方法中可以实现我们要处理的逻辑

2、在web.xml中添加自定义监听器的配置

<!--配置自定义的Session监听器-->
<listener>
    <listener-class>com.test.platform.web.util.authorization.MySessionListener</listener-class>
</listener>

3、在applicationContext.xml文件中将CustomerUserLoginLogServiceImpl交给spring容器管理

<bean id="customerUserLoginLogService" class="com.test.platform.core.system.implemented.CustomerUserLoginLogServiceImpl"></bean>

如有错误,欢迎指正

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值