본문 바로가기

기존카테고리/JSP

웹어플리케이션을 감시하는 리스너 ServletContextListener(contextInitialized(), contextDestroy())




ContextL_Ex.java



package com.test.ex;


import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


/**

 * Servlet implementation class ContextL_Ex

 */


// ServletContextListener(contextInitialized(), contextDestroy())

// 웹어플리케이션을 감시하는 리스너이다.

// 리스너의 해당하는 어플릴케이션이 시작, 종료 시에 호출된다. 


// 리스너를 제작하고, web.xml 리스너를 클래스를 정의


@WebServlet(name = "CL_Ex", urlPatterns = { "/CL_Ex" })

public class ContextL_Ex extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public ContextL_Ex() {

        super();

        // TODO Auto-generated constructor stub

    }


/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

System.out.println("App START~~~");

}


/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

}


}



-------------------------------------------------------------


ContextL.java


package com.test.ex;


import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;


public class ContextL implements ServletContextListener {


@Override

public void contextDestroyed(ServletContextEvent arg0) {

System.out.println("어플리케이션이 종료!!!");


}


@Override

public void contextInitialized(ServletContextEvent arg0) {

System.out.println("어플리케이션 시작");


}


}


--------------------------------------------------------------------


web.xml


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

  <display-name>servlet01</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>


<listener>

<listener-class>com.test.ex.ContextL</listener-class>

</listener>

</web-app>