[Spring] Servlet - 서블릿이란?

2025. 6. 20. 23:04·Spring/MVC

웹 서버의 가장 기본적인 구현 방식인 서블릿에 대해 먼저 알아보자.

서블릿은 클라이언트의 HTTP 요청 메시지를 기반으로 Request, Response를 파상한 객체를 자동으로 생성해준다.

이후 서블릿 컨테이너에서 해당 서블릿을 찾아 비즈니스 로직을 수행 한 후에, resonse를 생성하여 클라이언트에게 내려준다.

즉 복잡하게 생각할 것 없이, 개발자가 서블릿을 통한 비즈니스 로직 수행 이외의 모든 작업 (요청 파싱, 응답 생성) 등은 전부 스프링이 해준다는 점이다. 이 덕분에 서블릿은 온전히 본인의 작업만 수행할 수 있게 된다.

 

@ServletComponentScan

서블릿이 실행될 수 있는 가장 기본적인 조건은 WAS 를 설치하고,  그 위에 서블릿 코드를 올려서 빌드해야 실행된다는 점이다.

스프링부트는 이러한 번잡함을 해결하기 위해 @ServletComponentScan 에노테이션을 지원하여 ServerApplication 클래스에 달아두면 자동으로 패키지 내의 서블릿을 탐색하여 등록한다.

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);
	}

}

 

서블릿의 간단한 예시

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

// 참고로 name 옵션은 서블릿 컨테이너에 등록되는 서블릿의 이름 (스프링 빈과 유사하다)
@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);
    }
}

서블릿의 기본적인 동작 구조는 입력받은 URL을 기준(위 코드에선 /hello) 으로 해당 URL로 접속시 service 메서드를 실행한다.

해당 service() 메서드 내에서 Response응답을 모두 작성하여 클라이언트에게 내려준다.

위 코드는 간단하게 사용자의 이름을 쿼리 파라미터로 전송하면, 해당 이름을 hello + 이름 으로 출력해주는 서블릿이다.

여기서 우리가 봐야할 것은, service 메서드는 HttpServletRequest 와 HttpServletResponse 파라미터를 받는데, 이는 HttpServlet 이 지원하는 기능으로 요청 메시지와 응답 메시지를 자동으로 파싱해주는 편리한 기능이다.

예를 들어 위 코드에서는 아무런 파싱 로직이 없는데 getParameter("username") 메서드를 통해 단순하게 username을 알아낼 수 있었다.

또한 HttpServletResponse 는 Writer도 지원하기 때문에, Writer를 받아온 후 메시지 바디를 한번에 쓸 수도 있다.

이외에, 우리가 작성해줘야 하는 헤더들도 setXXX() 메서드를 통해 편리하게 작성할 수 있다.

 

이제 본격적으로 Request 부터 천천히 알아보자 !

그럼 20000 !

'Spring > MVC' 카테고리의 다른 글

[Spring] HTTP Response 데이터 처리하기  (0) 2025.06.21
[Spring] HttpServletResponse와 제공 메서드  (0) 2025.06.21
[Spring] HTTP Request 데이터를 처리하는 3가지 방법  (0) 2025.06.21
[Spring] HttpServletRequest과 제공 메서드  (0) 2025.06.20
[Spring] Web Server, Web Application Server(WAS)  (0) 2025.06.20
'Spring/MVC' 카테고리의 다른 글
  • [Spring] HttpServletResponse와 제공 메서드
  • [Spring] HTTP Request 데이터를 처리하는 3가지 방법
  • [Spring] HttpServletRequest과 제공 메서드
  • [Spring] Web Server, Web Application Server(WAS)
xuv2
xuv2
집에 가고 싶다
  • xuv2
    xuvlog
    xuv2
  • 전체
    오늘
    어제
    • 전체 글 모아보기 (171) N
      • 잡담 (9)
      • 도전 , 자격증 (2)
      • Error (5)
      • Java (23)
      • Spring (40) N
        • Core (10)
        • MVC (21) N
        • Thymeleaf (9)
      • DataBase (6)
        • Database Modeling (4)
        • SQL (2)
      • HTTP (11)
      • Network (17)
      • Software Engineering (3)
      • Operating System (3)
      • Algorithm (16)
      • Project (18)
        • Web (9)
        • iOS (8)
        • Python (1)
      • A.I (13)
      • Linux (5)
  • 블로그 메뉴

    • 홈
  • 링크

    • Github
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
xuv2
[Spring] Servlet - 서블릿이란?
상단으로

티스토리툴바