웹컨테이너에서 실행되는 각각의 웹 애플리케이션마다 한개씩의 ServletContext객체를 가지고 있다. ServletContext객체는 웹컨테이너가 시작될 때 생성되며 일단 생성되고 나면 웹애플리케이션에 접속하는 모든 이용자들이 ServletContext객체에 공유할 수 있게 된다. ServletContext객체는 영역 객체(Scope Object)이므로 setAttribute(), getAttribute()메소드를 이용하여 다른 객체를 저장할 수도 있으며, 다음 예제는 ServletContext객체가 생성될 때와 삭제될 때 웹컨테이너에 의해 호출되는 이벤트리스너를 사용하는 예이다.
ServletContext객체는 JSP에서 application이라는 참조변수로 사용하며, Servlet이나 JSP 양쪽 모두에서 getServletContext()메소드를 이용하여 참조를 얻어낼 수 있다.
package com.mycompany.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ServletListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("서블릿 컨텍스트 Destroyed");
ServletContext context = event.getServletContext();
}
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = null;
context = event.getServletContext();
// set variable to servlet context
context.setAttribute("TEST", "TEST_VALUE");
System.out.println("서블릿 컨텍스트 Initialized");
}
}
Okay, logically, if our web application is started, the contextInitialized method is executed. If our web application is removed (perhaps shutting down / redeploying web application in Tomcat), contextDestroyed method is executed.
서블릿이 리로딩될 때도 서블릿 컨텍스트 이벤트는 발생한다. 그러므로 reloadable=true 으로 설정된 웹애플리케이션의 서블릿을 수정하여 다시 저장하면 contextInitialized(), contextDestroyed() 메소드가 실행된다.
Now, we need to add one more entry in our web.xml.
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <listener> <listener-class> com.mycompany.listener.ServletListener </listener-class> </listener> </web-app>
One thing you need to know that this listener entry MUST be before the <servlet> entry (if any).