어노테이션을 이용한 초기화파라미터/리스너/필터 등록하기


어노테이션을 사용하기 위해 프로젝트의 웹 모듈 버전은 3.0 이상으로 설정해야 한다.

ServletConfig API를 활용한 초기화 파라미터 사용
초기화 파라미터는 여러 서블릿에서 공유해서 사용하지 못하고 등록된 서블릿에서만 사용할 수 있다.
(웹 애플리케이션 범위의 초기화 파라미터를 사용하려면 ServletContext API를 사용해야 한다.)

1
2
3
4
5
6
7
8
9
10
11
@WebServlet(name = "init", urlPatterns = { "/init" }, initParams = {
@WebInitParam(name = "dirPath", value = "D:\\test"), @WebInitParam(name = "id", value = "root") })
public class AnnoInitParam extends HttpServlet {
 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
        System.out.println(getInitParameter("dirPath")); // d:\\test
        System.out.println(getInitParameter("id"));      // root
    }
 
}
cs

ServletContextListener API
웹 애플리케이션도 서블릿처럼 라이프사이클을 가진다. 톰캣 컨테이너가 시작될 때 웹 애플리케이션도 초기화되고, 톰캣 컨테이너가 종료될 때 웹애플리케이션도 제거된다. ServletContextListener API를 사용하면 언제 초기화되고 제거 되는지를 쉽게 알 수 있다.
ex) JDBC Pooling - 웹 애플리케이션이 초기화될 때 Pooling을 활성화하고, 제거될 때 비활성화 시키면 효율적인 Connection 관리를 할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@WebListener
public class ContextListener implements ServletContextListener {
    
    @Override
    public void contextDestroyed(ServletContextEvent e) {
        System.out.println("웹 애플리케이션 종료");
    }
 
    @Override
    public void contextInitialized(ServletContextEvent e) {
        System.out.println("웹 애플리케이션 초기화");        
    }
 
}
cs

Filter API
클라이언트인 웹 브라우저와 웹 서버인 서블릿은 요청과 응답을 주고 받는다. Filter API를 사용하면 웹 브라우저에서 서블릿으로의 요청 전에 선처리와
서블릿에서 웹 브라우저로의 응답 전에 후처리가 가능하다. 또한, 다수의 필터를 체인처럼 묶어서 적용할 수 있다.

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
@WebFilter(urlPatterns = "/*")
public class AnnoFilter implements Filter {
 
    @Override
    public void destroy() {
        System.out.println("필터 제거");
    }
 
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("선처리 요청필터");
        req.setCharacterEncoding("UTF-8");
        
        chain.doFilter(req, resp); // 선.후처리 기준점
        
        System.out.println("후처리 응답필터");
        resp.setCharacterEncoding("UTF-8");
    }
 
    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("필터 초기화");
    }
    
}
cs


+ Recent posts