서론
ServletContextListener는 웹 애플리케이션의 생명주기를 관리하는 중요한 리스너 인터페이스입니다. 이 인터페이스를 사용하면 서블릿 컨테이너가 시작되거나 종료될 때 특정 코드를 실행할 수 있습니다. 본 글에서는 ServletContextListener의 구조와 활용 방법, 그리고 실제 사용 사례를詳細히 다루겠습니다.
ServletContextListener란?
ServletContextListener는 javax.servlet 패키지에 정의된 리스너 인터페이스로, 웹 애플리케이션의 전체 컨텍스트 수준에서 이벤트를 감지합니다. 이 리스너는 웹 애플리케이션이 Deploy될 때 초기화되고, 언Deploy될 때 소멸됩니다. 주로 웹 애플리케이션 전역에서 필요한 자원 초기화나 정리 작업에 사용됩니다.
인터페이스 구조
ServletContextListener는 EventListener를 확장하며, 두 개의 추상 메서드를 정의합니다:
public interface ServletContextListener extends EventListener {
public void contextInitialized(ServletContextEvent sce);
public void contextDestroyed(ServletContextEvent sce);
}
주요 메서드 설명
- contextInitialized(): 웹 애플리케이션이 시작될 때 한 번만 호출됩니다. 이 메서드에서 초기화 작업을 수행합니다.
- contextDestroyed(): 웹 애플리케이션이 종료될 때 호출됩니다. 자원 정리 작업을 수행합니다.
- getServletContext(): ServletContextEvent 객체에서 ServletContext 인스턴스를 가져옵니다.
실제 사용 예제
다음 예제는 애플리케이션 시작 시 캐시 시스템을 초기화하고 종료 시 정리하는 예제입니다:
package com.example.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashMap;
import java.util.Map;
public class CacheInitializerListener implements ServletContextListener {
private Map<String, Object> applicationCache;
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext application = event.getServletContext();
applicationCache = new HashMap<>();
applicationCache.put("userSessionTimeout", 1800);
applicationCache.put("maxLoginAttempts", 5);
applicationCache.put("enableCache", true);
application.setAttribute("systemCache", applicationCache);
System.out.println("캐시 시스템 초기화 완료");
System.out.println("캐시 항목 수: " + applicationCache.size());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
ServletContext application = event.getServletContext();
if (applicationCache != null) {
applicationCache.clear();
}
application.removeAttribute("systemCache");
System.out.println("리소스 정리 작업 완료");
}
}
web.xml 설정
리스너를 사용하려면 web.xml 파일에 다음과 같이 등록해야 합니다:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>com.example.listener.CacheInitializerListener</listener-class>
</listener>
</web-app>
애노테이션 방식 설정
서블릿 3.0 이상에서는 @WebListener 애노테이션을 사용하여 리스너를 등록할 수 있습니다:
package com.example.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class CacheInitializerListener implements ServletContextListener {
private Map<String, Object> applicationCache;
@Override
public void contextInitialized(ServletContextEvent event) {
this.applicationCache = new HashMap<>();
this.applicationCache.put("initialized", System.currentTimeMillis());
event.getServletContext().setAttribute("systemCache", this.applicationCache);
System.out.println("애플리케이션 캐시 초기화됨");
}
@Override
public void contextDestroyed(ServletContextEvent event) {
if (this.applicationCache != null) {
this.applicationCache.clear();
}
System.out.println("애플리케이션 캐시 정리됨");
}
}
응용 시나리오
ServletContextListener는 다양한 용도로 활용될 수 있습니다:
- 데이터베이스 커넥션 풀 초기화 및 종료
- 애플리케이션 전역 설정값 로드
- 캐시 시스템 구축
- 스케줄러 또는 타이머 시작
- 외부 서비스 연결 초기화
실행 순서
웹 애플리케이션이 시작될 때 리스너의 실행 순서는 다음과 같습니다:
- 서블릿 컨테이너가 웹 애플리케이션 로드를 시작
- ServletContextListener의 contextInitialized() 메서드 호출
- 필터(Filter) 초기화
- 서블릿(Servlet) 초기화
결론
ServletContextListener는 웹 애플리케이션의 생명주기 관리에 필수적인 인터페이스입니다. 이 리스너를 활용하면 애플리케이션 시작 시 필요한 자원을 초기화하고 종료 시 적절하게 정리할 수 있습니다. 올바른 리스너 구현은 애플리케이션의 안정성과 성능에 중요한 역할을 합니다.