【JavaWeb】用监听器实现单一登录

导读:监听器用来监视ServletContext/Session/Request的创建、初始化、销毁以及其中的属性变动。


监听器的分类

常见的主要有以下6个,分别处理Servlet全局、Session和Request。

  • ServletContextListener
  • ServletContextAttributeListener
  • HttpSessionListener
  • HttpSessionAttributeListener
  • ServletRequestListener
  • ServletRequestAttributeListenser

监听器的作用

由于每当一个用户访问一个网站都会产生一个会话或是一个请求,所以可以使用监听器来监视这些会话和请求,能够用于

  • 统计在线人数
  • 统计访问量
  • 应用启动时信息初始化
  • 与Spring结合

监听器的实现

根据需要实现上述的六种接口,对象监听器实现Init和Destroy方法,属性监听器实现Add/Remove/Replace方法。然后在web.xml中对监听器进行配置,相比于Servlet和Filter,监听器的配置更为简单。

ServletContextListener举例

public class MyServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String appName=sce.getServletContext().getInitParameter("app_name");
        String version=sce.getServletContext().getInitParameter("version");
        sce.getServletContext().setAttribute("app_name",appName);
        sce.getServletContext().setAttribute("version",version);
        System.out.println("Init:"+appName+"  "+version);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        String appName=(String)sce.getServletContext().getAttribute("app_name");
        String version=(String)sce.getServletContext().getAttribute("version");
        System.out.println("Destroy:"+appName+"  "+version);
    }
}

在web.xml中进行配置,设置全局属性,用于获取。

<context-param>
    <para
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值