서블릿은 톰캣 같은 웹 애플리케이션 서버를 직접 설치하고, 그 위에 서블릿 코드를 클래스 파일로 빌드해서 올린 다음, 톰캣 서버를 실행하면 됩니다. 하지만 이 과정은 매우 번거롭습니다.

스프링 부트는 톰캣 서버를 내장하고 있으므로, 톰캣 서버 설치 없이 편리하게 서블릿 코드를 실행할 수 있습니다.

그래서 스프링 부트 환경에서 서블릿을 등록하고 사용해보겠습니다.

스프링 부트 서블릿 환경 구성

package hello.servlet;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@ServletComponentScan //서블릿 자동 등록 ...1
@SpringBootApplication
public class ServletApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServletApplication.class, args);
	}

}
  1. 스프링 부트에서 서블릿을 쓰기 위해서 @ServletComponentScan 을 지원합니다.

서블릿 등록하기

처음으로 실제 동작하는 서블릿 코드를 등록해보겠습니다.

hello.servlet.basic 패키지를 만들고 HelloServlet 클래스를 만듭니다.

package hello.servlet.basic;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "helloServlet", urlPatterns = "/hello") //...2
public class HelloServlet extends HttpServlet { //...1

		//...3
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("HelloServlet.service");
    }
}
  1. 서블릿은 HttpServlet을 상속 받아야합니다.

  2. @WebServlet(name = "helloServlet", urlPatterns = "/hello")

  3. service()

    <aside> 🌟 [TIP]

    Control + O : 오버라이드 할 수 있는 메서드 찾기

    Untitled

    열쇠 표시가 있는 메서드가 protected 입니다.

    </aside>

먼저 실행이 되는지 한 번 봅시다.

꼭 8080 포트번호로 실행이 되는 것을 확인합시다.

Untitled