오늘은 Java기반의 웹 서버인 서블릿에 대해서 알아보자
@ServletComponentScan
스프링 부트는 서블릿을 직접 등록해서 사용할 수 있도록 @ServletComponentScan 을 지원한다. 다음과 같이 추가하자.
package hello.servlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan //서블릿 자동 등록
@SpringBootApplication
public class ServletApplication {
public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}
서블릿 등록하기
@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
System.out.println("HelloServlet.service");
System.out.println("request = " + request);
System.out.println("response = " + response);
String username = request.getParameter("username");
System.out.println("username = " + username);
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
response.getWriter().write("hello " + username);
}
}
여기서 servlet container란 무엇일까?
컨테이너의 동작 방식을 좀 더 자세하게 살펴보자
1. 사용자(클라이언트)가 URL을 통해 요청을 보내면 HTTP Request를 Servlet Conatiner가 받도록 bind되어있다.
2. HTTP Request를 전송받은 Servlet Container는 http message를 파싱하여 HttpServletRequest, HttpServletResponse 두 객체를 생성한다.
3. (web.xml은 사용자가) 그 다음에는 요청한 URL을 분석하여 어느 서블릿에 대해 요청을 한 것인지 라우팅한다.
4. 해당 서블릿에서 service메소드를 호출한 후 POST, GET여부에 따라 doGet() 또는 doPost()를 호출.
5. doGet() or doPost() 메소드는 적절한 처리 후 HttpServletResponse객체에 응답을 보냅니다.
6. 응답이 끝나면 HttpServletRequest, HttpServletResponse 두 객체를 소멸시킨다.
서블릿 생명주기(Servlet Lifecycle)
서블릿 컨테이너는 요청이 처음 들어왔을 때 현재 실행할 서블릿이 최초의 요청인지 판단하고 없으면 해당 서블릿을 새로 생성한다. 이 작업은 최초 1회만 일어난다.
참고