public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Context Initialized");
sce.getServletContext().setAttribute("name", "spring");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("Context Destroyed");
}
}
<web-app>
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>org.example.servlet02.MyListener</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.example.servlet02.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
public class HelloServlet extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("init");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet");
resp.getWriter().println("<html>");
resp.getWriter().println("<head>");
resp.getWriter().println("<body>");
resp.getWriter().println("<h1>Hello, " + getservletContext().getAttribute("name") + "</h1>");
resp.getWriter().println("Hello Servlet");
resp.getWriter().println("</body>");
resp.getWriter().println("</head>");
resp.getWriter().println("</html>");
}
private Object getName() {
return getServletContext().getAttribute("name");
}
@Override
public void destroy() {
System.out.println("destroy");
}
}
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Filter Init");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("filter");
chain.doFilter(request, response);
}
@Override
public void destroy() {
System.out.println("Filter Destroy");
}
}
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>myFilter</filter-name>
<filter-class>org.example.servlet02.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<servlet-name>hello</servlet-name>
</filter-mapping>
<listener>
<listener-class>org.example.servlet02.MyListener</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.example.servlet02.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
서블릿 리스너가 서블릿 초기화 이벤트 감지(contextInitialized) -> 필터가 초기화(init) -> 서블릿 초기화(init) -> 필터 실행(doFilter) -> 서블릿 실행(doGet) -> 서블릿 종료(destroy) -> 필터 종료(destroy) -> 서블릿 리스너가 서블릿 종료 이벤트 감지(contextDestroyed)
참고