public class MyServletContextListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent event){
//数据库连接代码
}
public void contextDestroyed(ServletContextEvent event){
//关闭数据库连接代码
}
}
下面是一个应用实例对与监听器的使用
public class MyServletContextListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent event){
//数据库连接代码
ServletContext sc = event.getServletContext();
String dogBreed = sc.getInitParameter("breed");
Dog d = new Dog(dogBreed);
sc.setAttribute("dog",d);//利用上下文设置属性,在其他地方就可以获得属性
}
public void contextDestroyed(ServletContextEvent event){
//关闭数据库连接代码
}
}
public class Dog{
private String breed;
public Dog(String breed){
this.breed = breed;
}
public String getBreed(){
return breed;
}
}
public class ListenerTester extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws Excepton{
response.setContentType("text/html");\
PrintWriter out = response.getWriter();
Dog dog = (Dog)getServletContext().getAttribute("dog");
out.println(dog.getBreed());
}
}