서블릿 컨테이너는 웹 애플리케이션의 상태를 관리하는 ServletContext를 생성한다.
ServletContext가 초기화되면 컨텍스트의 초기화 이벤트가 발생한다.
등록된 ServletContextListener의 콜백 메서드인, contextInitialized() 메서드가 호출된다.
@WebListener
public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScript(new ClassPathResource("jwp.sql"));
DatabasePopulatorUtils.execute(populator, ConnectionManager.getDataSource());
logger.info("Completed Load ServletContext!");
}
}
데이터베이스 초기화
jwp.sql 파일에서 SQL 문을 실행해 데이터베이스 테이블을 초기화한다.
DispatcherServlet 인스턴스 생성
서블릿 컨테이너는 클라이언트로부터의 최초 요청시( 혹은 컨테이너에 서블릿 인스턴스를 생성하도록 미리 설정을 한다면 최초 요청 전에 ) DispatcherServlet 인스턴스를 생성한다(생성자 호출). 이에 대한 설정은 @WebServlet의 loadOnStartup 속성으로 설정할 수 있다.
DispatcherServlet 인스턴스의 init() 메서드를 호출해서 초기화 작업을 진행한다.
public class RequestMapping {
void initMapping() {
mappings.put("/", new HomeController());
mappings.put("/users/form", new ForwardController("/user/form.jsp"));
mappings.put("/users/loginForm", new ForwardController("/user/login.jsp"));
mappings.put("/users", new ListUserController());
mappings.put("/users/login", new LoginController());
mappings.put("/users/profile", new ProfileController());
mappings.put("/users/logout", new LogoutController());
[ 생략 ..]
}
}