티스토리 뷰
컨텍스트 리스너
컨텍스트 리스너는 웹 어플리케이션(컨텍스트)이 시작되거나 중지될 때, 그 알림을 받는 녀석입니다.
컨텍스트 리스너를 생성하는 방법
컨텍스트 리스너를 생성하기 위해서는 ServletContextListener 인터페이스를 구현하는 클래스를 만들어야 합니다.
이는 다음 두 메쏘드를 구현해야 함을 말합니다.
public void contextInitialized(ServletContextEvent servletContextEvent);
public void contextDestroyed(ServletContextEvent servletContextEvent);
각각의 리스너 클래스는 매개변수가 없는 생성자를 꼭 가지고 있어야 합니다.
contextInitialized()
이 메쏘드는 어플리케이션이 시작될 때 호출됩니다.
contextDestroyed()
이 메쏘드는 어플리케이션이 중지될 때 호출됩니다.
ServletContext
ServletContext 가 ServletContextEvent 객체로부터 위 두개의 메쏘드로 전달되어집니다.
이것은 아래처럼 추적할 수 있습니다.
ServletContext servletContext = servletContextEvent.getServletContext();
이 객체는 컨텍스트 특징정보를 저장하는데 쓰이는 setAttribute(), getAttribute() 와 removeAttribute() 메쏘드를 가집니다.
전체 예제
import javax.servlet.*;
public final class MyContextListener
implements ServletContextListener {
public MyContextListener() {
}
public void contextInitialized(ServletContextEvent servletContextEvent) {
// 컨텍스트를 얻어옵니다.
ServletContext servletContext = servletContextEvent.getServletContext();
// 컨텍스트 속성을 설정합니다.
try {
System.out.println("[MyContextListener] Application X is starting");
servletContext.setAttribute("foo", "bar");
} catch (Exception e) {
System.out.println("[MyContextListener] Error setting context attribute: " + e.getMessage());
}
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
// 컨텍스트를 얻어옵니다.
ServletContext servletContext = servletContextEvent.getServletContext();
// 위에서 세팅했던 컨텍스트 정보를 출력합니다.
System.out.println("[MyContextListener] Application X is shutting down");
System.out.println("[MyContextListener] Value of foo is: " + servletContext.getAttribute("foo"));
// 컨텍스트 정보를 삭제합니다. ( 꼭 필요한 건 아니지만, 깔금하게 )
servletContext.removeAttribute("foo");
}
}
web.xml에 컨텍스트 리스너를 추가하는 방법
위에서 만든 클래스를 WEB-INF/classes 에 추가하고, web.xml에 다음 내용을 추가해서 컨텍스트 리스너를 동작시킵니다.
<listener>
<listener-class>MyContextListener</listener-class>
</listener>
원본출처 : http://wiki.metawerx.net/wiki/ContextListener
- Total
- Today
- Yesterday
- 여행
- LG
- 전북
- spring tutorial
- 세부
- Spring
- K리그
- SqlSessionfactory
- MySQL
- 카메라
- 톰캣
- 펜탁스
- 리조트
- 스프링부트
- k-3
- 사이판
- G3
- 자바
- 캠핑장
- 에닝요
- web.xml
- 스프링
- Java
- 캠핑
- PIC
- 텐트
- mybatis
- 아마존
- 부모님
- 강원도
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |