ServletContextListener 실습

Byung Seon Kang·2022년 9월 26일
0

서블릿에 대해

목록 보기
3/9

코드

tomcat/webapps/listenerTest/WEB-INF/web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
        version="2.4">
    <servlet>
        <servlet-name>ListenerTester</servlet-name>
        <servlet-class>com.example.servlet.ListenerTester</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ListenerTester</servlet-name>
        <url-pattern>/ListenTest.do</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>breed</param-name>
        <param-value>Great Dane</param-value>
    </context-param>
    <listener>
        <listener-class>
            com.example.servlet.MyServletListener
        </listener-class>
    </listener>
</web-app>
  • ListenerTester라는 servlet 설정
  • context-param을 통해 ServletContext 속성 설정해서 전체 servlet이 이를 활용할 수 있도록 설정해줌.
  • 마지막으로 listener class 설정.

/usr/local/tomcat10/webapps/listenerTest/WEB-INF/classes/com/example/servlet 내부

MyServletListener

package com.example.servlet;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

public class MyServletListener  implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event){
       ServletContext sc = event.getServletContext();
        String dogBreed = sc.getInitParameter("breed");
        Dog d = new Dog(dogBreed);
        sc.setAttribute("dog", d);
    }

    public void contextDestroyed(ServletContext event) {
		//이거 왜 만들었는지 잘 모르겠다.
    }
}

Tester

package com.example.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

public class ListenerTester extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws IOException, ServletException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Dog dog = (Dog) getServletContext().getAttribute("dog");
        out.println("this is my servlet test");
        out.println("Dog breed is " + dog.getBreed());

    }
}

Dog class

package com.example.servlet;

public class Dog {
    private String breed;

    public Dog(String breed){
        this.breed = breed;
    }

    public String getBreed(){
        return breed;
    }
}

compile 명령어는 위 코드를 작성한 곳에서
javac ./*.java 를 사용했다.

실행 결과


다음과같이 context의 param을 잘 읽어옴을 확인했다.

profile
왜 필요한지 질문하기

0개의 댓글