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>
/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을 잘 읽어옴을 확인했다.