[Servlet] Listener

컨테이너·7일 전
0

SpringFramework

목록 보기
10/15
post-thumbnail

01. Servlet Listener 정리

01-01. Listener 개요

01-01-01. Servlet Listener란

웹 컨테이너(Tomcat) 내부에서 일어나는 이벤트를 감지하고 자동으로 실행되는 클래스이다.

Servlet, Filter는 사용자 요청을 다루지만,

Listener는 서버 내부 객체의 생성/소멸·속성 변경을 감시한다.

동작 예:

  • 웹 애플리케이션이 켜질 때 알림
  • 세션이 생성되거나 만료될 때 알림
  • request가 만들어지고 사라질 때 알림
  • session·request·context에 attribute 추가/삭제/수정 감지

즉, 프로그램 전체 흐름의 “감시자” 역할.


01-01-02. Listener 동작 구조

컨테이너가 이벤트를 발생시키면 Listener가 즉시 반응한다.

Context 시작 → Listener 반응
Session 생성 → Listener 반응
Request 들어옴 → Listener 반응
Attribute 추가 → Listener 반응

01-01-03. Listener를 사용하는 경우

  1. Context 레벨 이벤트
    • 웹 애플리케이션 시작/종료
    • ServletContext attribute 값의 추가·삭제·변경
  2. Session 레벨 이벤트
    • 세션 생성/만료
    • 세션 attribute 추가·삭제·변경
    • 세션에 객체가 바인딩/언바인딩
  3. Request 레벨 이벤트
    • request 생성/소멸
    • request attribute 추가·삭제·변경

02. Servlet Listener 종류

Listener는 관찰 대상에 따라 크게 3종류로 나뉜다.

  1. Context Listener
  2. Session Listener
  3. Request Listener

그리고 각 객체의 attribute 변화를 감지하는 Attribute Listener가 존재한다.


02-01. Context Listener

1. ServletContextListener

웹 애플리케이션 전체의 시작과 종료 감지

  • contextInitialized(): 웹 애플리케이션 시작 시
  • contextDestroyed(): 웹 애플리케이션 종료 시

주로 하는 일:

  • 서버가 켜질 때 초기 데이터 로딩
  • DB 연결 풀 생성
  • 종료 시 자원 해제

2. ServletContextAttributeListener

ServletContext 내부에 저장된 attribute 값 변화 감지

  • attributeAdded()
  • attributeRemoved()
  • attributeReplaced()

Application 전체에서 공유하는 값을 감시할 때 사용.


02-02. Session Listener

1. HttpSessionListener

세션 생성/만료 감지

  • sessionCreated(): 세션 생성
  • sessionDestroyed(): 세션 만료 또는 invalidate()

예: 방문자 수 카운트, 로그인 수 확인


2. HttpSessionAttributeListener

Session의 attribute 변화 감지

  • attributeAdded()
  • attributeRemoved()
  • attributeReplaced()

예: 로그인 정보 저장/변경 감지


3. HttpSessionBindingListener

“세션에 저장된 객체" 자체가 이벤트를 감지한다.

객체가 세션에 들어갈 때(valueBound),

세션에서 제거될 때(valueUnbound) 호출된다.

예:

  • 사용자 객체(UserDTO)가 세션 바인딩 시점 감지
  • 특정 객체가 세션에서 제거될 때 처리

4. HttpSessionActivationListener

세션 활성화/비활성화 감지

웹 서버가 여러 대일 때(세션 클러스터링) 사용되며,

세션을 다른 서버로 옮길 때(Session Migration)를 감지한다.

  • sessionDidActivate()
  • sessionWillPassivate()

02-03. Request Listener

1. ServletRequestListener

request 생성/소멸 감지

  • requestInitialized(): request가 처음 만들어질 때
  • requestDestroyed(): request가 끝날 때

예:

  • 요청마다 접속 IP 로깅
  • 전체 요청 처리 시간 측정

2. ServletRequestAttributeListener

request attribute 변화 감지

  • attributeAdded()
  • attributeRemoved()
  • attributeReplaced()

Forward할 때 데이터 전달 과정 감시 등에 활용.


03. Servlet Listener 예제 요약

03-01. Context Listener 예시

@WebListener
public class ContextListenerTest implements ServletContextListener, ServletContextAttributeListener {

    public ContextListenerTest() {
        System.out.println("context listener 인스턴스 생성");
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("context init");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("context destroy");
    }

    @Override
    public void attributeAdded(ServletContextAttributeEvent scae) {
        System.out.println("context attribute added");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent scae) {
        System.out.println("context attribute removed");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent scae) {
        System.out.println("context attribute replaced");
    }
}

03-02. Session Listener 예시

@WebListener
public class SessionListenerTest implements HttpSessionListener, HttpSessionAttributeListener {

    public SessionListenerTest() {
        System.out.println("session listener 인스턴스 생성");
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session created");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session destroyed");
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        System.out.println("session attribute added: " + se.getName());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        System.out.println("session attribute removed: " + se.getName());
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {
        System.out.println("session attribute replaced: " + se.getName());
    }
}

HttpSessionBindingListener 객체 예시

public class UserDTO implements HttpSessionBindingListener {

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("UserDTO 세션 바인딩");
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("UserDTO 세션 언바인딩");
    }
}

03-03. Request Listener 예시

@WebListener
public class RequestListenerTest implements ServletRequestListener, ServletRequestAttributeListener {

    public RequestListenerTest() {
        System.out.println("request listener 인스턴스 생성");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("request init");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("request destroy");
    }

    @Override
    public void attributeAdded(ServletRequestAttributeEvent srae) {
        System.out.println("request attribute added");
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent srae) {
        System.out.println("request attribute removed");
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent srae) {
        System.out.println("request attribute replaced");
    }
}

04. Listener 개념 전체 요약

  1. Listener는 웹 컨테이너 내부 이벤트를 감지하는 클래스이다.
  2. Context, Session, Request 세 객체의 생성/소멸을 감지한다.
  3. Attribute Listener는 각 객체 내부의 데이터 변화를 감지한다.
  4. Filter는 요청/응답을 다루고, Listener는 서버 내부 이벤트를 다룬다.
  5. 주요 사용처
    • 애플리케이션 초기 설정
    • 세션 관리 및 로그인 상태 추적
    • 요청 로깅
    • attribute 기반 데이터 변화 감지
    • 세션 클러스터링 환경 대응

profile
백엔드

0개의 댓글