[스프링 부트] chapter 5. 내장 서블릿 컨테이너
내장 서블릿 컨테이너
자바 코드로 서버를 생성할 수 있음
-
톰캣 객체 생성
-
포트 설정
-
톰캣에 컨텍스트 추가
-
서블릿 만들기
-
톰캣에 서블릿 추가
-
컨텍스트에 서블릿 매핑
-
톰캣 실행 및 대기
public static void main(String[] args) {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
Context context = tomcat.addContext("/", "/");
HttpServlet servlet = new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
PrintWriter writer = req.getWriter();
writer.println("<html><head><title>");
writer.println("Hey, Tomcat");
writer.println("</tltle></head>");
writer.println("<body><h1>Hello Tomcat</h1></body>");
writer.println("</html>");
}
};
String servletName = "helloServlet";
tomcat.addServlet("/", servletName, sevlet);
context.addServletMappingDecoded("/hello", servletName);
tomcat.start();
tomcat.getServer().await();
}
spring-boot-autoconfigure에서 ServletWebServerFactoryAutoConfiguration을 보면
위의 톰캣 설정보다 자세한 설정들을 볼 수 있고, DispatcherServletAutoConfiguration을 보면
서블릿을 만들고 등록하는 설정들을 확인 할 수 있다.
기본 웹서버인 톰캣을 사용하지 않으려면?
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
</dependencies>
프로퍼티로 웹 어플리케이션 타입 변경
application.properties에
spring.main.web-application-type=none
으로 설정하면 됨.
웹서버 기동시 자동 실행되야 되는 클래스가 있다면?
@Component
public class PortListener implements ApplicationListener<ServletWebServerInitializedEvent> {
@Override
public void onApplicationEvent(ServletWebServerInitializedEvent servletWebServerInitializedEvent) {
ApplicationContext applicationContext = servletWebServerInitializedEvent.getApplicationContext();
applicationContext.getWebServer().getPort();
}
}