스프링부트 서블릿 등록, 사용

@ServletComponentScan

스프링 부트는 서블릿을 직접 등록해서 사용할 수 있도록 @ServletComponentScan 을 지원한다.
다음과 같이 추가하자.

 

@WebServlet

서블릿 애노테이션 name: 서블릿 이름 urlPatterns: URL 매핑

 

hello.servlet.ServletApplication

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

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

서블릿 컨테이너 동작방식

HttpServletRequest

HttpServletRequest 역할

HTTP 요청 메시지를 개발자가 직접 파싱해서 사용해도 되지만, 매우 불편할 것이다.
서블릿은 개발자가 HTTP 요청 메시지를 편리하게 사용할 수 있도록 개발자 대신에 HTTP 요청 메시지를 파싱한다.
그리고 그 결과를 HttpServletRequest 객체에 담아서 제공한다.

HttpServletRequest를 사용하면 다음과 같은 HTTP 요청 메시지를 편리하게 조회할 수 있다.

HTTP 요청 메시지

POST /save HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded

username=kim&age=20

HttpServletRequest 개요

START LINE

  • HTTP 메소드
  • URL
  • 쿼리 스트링
  • 스키마, 프로토콜 헤더

헤더

  • 헤더 조회

바디

  • form 파라미터 형식 조회
  • message body 데이터 직접 조회

HttpServletRequest 객체는 추가로 여러가지 부가기능도 함께 제공한다.

 

임시 저장소 기능

  • 해당 HTTP 요청이 시작부터 끝날 때 까지 유지되는 임시 저장소 기능
    - 저장: request.setAttribute(name, value)
    - 조회: request.getAttribute(name)

세션 관리 기능

request.getSession(create: true)

HttpServletResponse

HttpServletResponse 역할

  • HTTP 응답 메시지 생성
  • HTTP 응답코드 지정 헤더 생성
  • 바디 생성

 

편의 기능 제공

  • Content-Type, 쿠키, Redirect

 

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

MVC 프레임워크 만들기  (0) 2022.07.16
서블릿, JSP, MVC 패턴  (0) 2022.07.16
HTML, HTTP API, CSR, SSR  (0) 2022.07.03
동시요청 - 멀티 스레드  (0) 2022.07.02
서블릿, 서블릿 컨테이너  (0) 2022.06.05

+ Recent posts