listener的应用

1  ServletContext(application)对象

 

package net.company.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.company.service.DepartmentService;
import net.company.service.DepartmentServiceBean;
import net.company.service.EmployeeService;
import net.company.service.EmployeeServiceBean;
import net.company.util.TxManagerProxy;

/**
 * ServletContext对象
 *    |-->服务器启动时创建,每个Web应用有一个
 *    |-->可以被所有Servlet所共享
 */
     
public class MyContextListener implements ServletContextListener {

 public void contextDestroyed(ServletContextEvent arg0) {
   ServletContext context=arg0.getServletContext();
   context.removeAttribute("departmentService");
   context.removeAttribute("employeeService");
   System.out.println("==ServletContextListener destroy==");
 }

 public void contextInitialized(ServletContextEvent arg0) {
   
          ServletContext context=arg0.getServletContext();
          //从代理对象中获得departmentService的对象,放到servletContext(application)对象中,类似spring中 的静态注入
          context.setAttribute("departmentService", (DepartmentService)new TxManagerProxy().getInstance(new DepartmentServiceBean()));
          context.setAttribute("employeeService", (EmployeeService)new TxManagerProxy().getInstance(new EmployeeServiceBean()));
          System.out.println("==ServletContextListener init==");
 }

}

 在action中通过

 private EmployeeService es=(EmployeeService)ServletActionContext.getServletContext().getAttribute("departmentService");获取对象

 

2 、sessionContext(session对象)

 

package net.company.web.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
 *监听Session(会话)对象的创建
 *  |--->http(1.1)-->无状态协议(在这个协议中不会保存会话(客户端与服务端进行通讯的过程)状态)
 *    |-->TCP/IP(四层)
 *      |-->应用层
 *      |-->网络层(网际层)
 *      |-->数据链路层
 *      |-->物理层
 *    |-->ISO(七层协议)
 **/
public class MySessionListener implements HttpSessionListener {

 public void sessionCreated(HttpSessionEvent arg0) {
  //Session创建

 }

 public void sessionDestroyed(HttpSessionEvent arg0) {
  
  //Session销毁

 }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值