Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 31
Tags more
Archives
Today
Total
관리 메뉴

David의 블로그

[JSP/Servlet]Listener 리스너 본문

프로그래밍/Jsp_Servlet

[JSP/Servlet]Listener 리스너

David 리 2023. 12. 19. 22:37

[Listener란??]

서블릿은 다양한 시점에서 발생하는 이벤트와 이벤트를 처리하기 위한 인터페이스를 정의하고 있다.

이 인터페이스를 이용하면 데이터의 초기화나 요청 처리 등을 추적할 수 있다.

서블릿에서 여러 Listener를 제공하고 있는데,

오늘은 ServletContextListener 인터페이스 활용 방법을 알아보겠다.

 

 

[web.xml]

먼저 Listener를 등록하기 위해서는 web.xml에

<listener>태그에다가 반드시 하위태그로 <listener-class>태그를 써야 한다.

쉽게 말해, <listener>는 하나의 Listener만 등록할 수 있다.

또, <listener-class>는 Listener로 등록할 클래스 패키지 경로를 적어주면 된다.

 

다음은

그 밑에있는 <context-param>태그는 context 초기화 파라미터를 세팅할 태그이다.

하위 태그로 <param-name>과 <param-value>태그를 갖는다.

나는 이 <context-param>으로 등록한 context 초기화 파라미터를 Listener 클래스로 구현한 DBCPInitListener에서 파라미터로 쓸 것이다.

 

 

[DBCPInitListener.java]

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package jdbc;
 
import java.io.StringReader;
import java.sql.DriverManager;
import java.util.Properties;
 
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
import org.apache.tomcat.dbcp.dbcp2.ConnectionFactory;
import org.apache.tomcat.dbcp.dbcp2.DriverManagerConnectionFactory;
import org.apache.tomcat.dbcp.dbcp2.PoolableConnection;
import org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory;
import org.apache.tomcat.dbcp.dbcp2.PoolingDriver;
import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPool;
import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPoolConfig;
 
// ServletContextListener 인터페이스를 상속 받는다.
public class DBCPInitListener implements ServletContextListener{
    
    // 웹 어플리케이션이 종료될 때, servletContextListener 객체가 삭제되는 메소드
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub
        
    }
 
    // 1. 웹 어플리케이션이 종료될 때, servletContextListener 객체가 생성되는 메소드
    // 2. ServletContextEvent 클래스는 웹 어플리케이션 컨텍스트를 구할 수 있는 getServletContext()메소드를 제공한다.
    // 3. getServletContext()메소드가 리턴하는 ServletContext 객체는 JSP의 application 기본 객체와 동일한 객체로,
    // web.xml 파일에 설정된 컨텍스트 초기화 파라미터를 구할 수 있다.
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // TODO Auto-generated method stub
        String poolconfig = 
            // 1. String getInitParameter() : 지정한 이름을 갖는 context 초기화 파리미터 값을 리턴. 
            // 존재하지 않을 경우 null을 리턴.
            // 파라미터로는 <param-name> 태그로 지정한 이름을 넣어주면 된다.
            sce.getServletContext().getInitParameter("poolConfig");
            
            //2. java.util.Enumeration<String> getInitParameterNames() : context 초기화 파라미터 이름 목록을 Enumeration타입으로 리턴.
                
        Properties prop = new Properties();
        try {
            // "키=값"형식으로 구성된 문자열로부터 프로퍼티를 로딩한다.
            // web.xml의 <context-param>의 poolconfig 초기화 파라미터 설정 값을 Properties객체에 프로퍼티로 등록을 한다.
            prop.load(new StringReader(poolconfig));
        } catch (Exception e) {
            // TODO: handle exception
            // contextInitialized()메소드 정의에 throws가 없어서 RunctimeException을 발생시킨다.
            throw new RuntimeException();
        }
        // JDBC드라이버 로드
        loadJDBCDriver(prop);
        // connectionPool 생성
        initConnectionPool(prop);
        
        
        
        System.out.println(poolconfig);
        
    }
    
    private void loadJDBCDriver(Properties prop) {
        // poolconfig 초기화 파라미터 설정 값 중 jdbcdriver 값.
        String driverClass = prop.getProperty("jdbcdriver");
        try {
            Class.forName(driverClass);
            
        } catch (ClassNotFoundException e) {
            // TODO: handle exception
            throw new RuntimeException("fail to load JDBC Driver", e);
        }
    }
    
    private void initConnectionPool(Properties prop) {
        try {
                // poolconfig 초기화 파라미터 설정 값 중 jdbcUrl, dbUser, dbPass 값.
                String jdbcUrl = prop.getProperty("jdbcUrl");
                String username = prop.getProperty("dbUser");
                String pw = prop.getProperty("dbPass");
                
                ConnectionFactory connFactory =
                        new DriverManagerConnectionFactory(jdbcUrl, username, pw);
                
                PoolableConnectionFactory poolableConnFactory = 
                        new PoolableConnectionFactory(connFactory, null);
                poolableConnFactory.setValidationQuery("select 1");
    
                GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
                poolConfig.setTimeBetweenEvictionRunsMillis(1000L * 60L * 5L);
                poolConfig.setTestWhileIdle(true);
                poolConfig.setMinIdle(5);
                poolConfig.setMaxTotal(50);
    
                GenericObjectPool<PoolableConnection> connectionPool = 
                        new GenericObjectPool<>(poolableConnFactory, poolConfig);
                poolableConnFactory.setPool(connectionPool);
                
                Class.forName("org.apache.commons.dbcp2.PoolingDriver");
                PoolingDriver driver = (PoolingDriver)
                    DriverManager.getDriver("jdbc:apache:commons:dbcp:");
                String poolName = prop.getProperty("poolName");
                driver.registerPool(poolName, connectionPool);
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
        
        
    }
    
}
 
cs

19번 라인 : Listener 클래스로 등록한 클래스. ServletContextListener 인터페이스를  구현한다.(implements)

23번 라인 : contextDestroyed() --> 웹 어플리케이션이 종료 될 때, ServletContextListener 객체가 삭제되는 메소드.

35번 라인 : 파리미터 ServletContextEvent 클래스는 웹 어플리케이션 컨텍스트를 구할 수 있는 getServletContext() 메소드를 제공한다.

47번 라인 : Properties.load() 메소드는 "키 = 값" 형식으로 구성된 문자열로부터 프로퍼티를 로딩한다.

web.xml에서 <param-name>으로 등록한 poolconfig 설정 값을 Properties 객체에 프로퍼티로 등록한다.

 

 

 

[어노테이션으로 Listener 등록하기]

web.xml에 등록할 필요없이 Listener로 사용하고자 하는 클래스에

@WebListener를 적어주기만 하면 된다.