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销毁
}
}