pebblepark
개발계발
pebblepark
전체 방문자
오늘
어제
  • 분류 전체보기 (24)
    • Frontend (7)
    • Backend (7)
    • 인프라 (1)
    • CS (0)
      • Design Pattern (0)
    • 정리용 (9)
    • 회고 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • CORS
  • 스프링 의존관계
  • TDZ
  • vite
  • 스프링 빈
  • useLayoutEffect
  • 스프링 컨테이너
  • hoisting
  • ERR_UNSAFE_PORT
  • Git
  • redux
  • github
  • 무한스크롤
  • spring
  • springboot
  • react-query
  • 리액트쿼리
  • wsl
  • 스프링
  • Docker
  • typescript
  • Github Pages
  • debounce
  • javascript
  • @ModelAttribute
  • 호이스팅
  • react
  • SpringMVC
  • Context API
  • React Query

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
pebblepark

개발계발

[Spring] Spring Boot에서 Servlet 사용하기
Backend

[Spring] Spring Boot에서 Servlet 사용하기

2022. 1. 11. 01:07
  • 스프링 부트 환경에서 서블릿을 등록하고 사용해보자

스프링 부트는 톰캣 서버를 내장하고 있음 -> 별도의 톰캣 서버 설치 없이 서블릿 코드 실행이 가능함

환경 구성

  • Gradle Project
  • Spring Boot 2.6.2

build.gradle

plugins {
    id 'org.springframework.boot' version '2.6.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'war'
}

group = 'hello'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

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

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

}
  • @ServletComponentScan : 서블릿을 직접 등록할 수 있도록 스프링 부트에서 지원

 

서블릿 등록

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 req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet.service");
        System.out.println("request = " + req);
        System.out.println("response = " + resp);

        String username = req.getParameter("username");
        System.out.println("username = " + username);

        resp.setContentType("text/plain");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write("hello " + username);
    }
}
  • @WebServlet: 서블릿 어노테이션
    • name: 서블릿 이름
    • urlPatterns: URL 매핑 주소

 

HTTP 요청 -> 매핑 URL 호출 -> 서블릿 컨테이너가 아래의 메서드 실행
protected void service(HttpServletRequest req, HttpServletResponse resp)

 

실행결과

  • http://localhost:8080/hello?username=world
HelloServlet.service
request = org.apache.catalina.connector.RequestFacade@25780651
response = org.apache.catalina.connector.ResponseFacade@2bbfec8e
username = world

 

서블릿 컨테이너 동작 방식

  • 웹 브라우저에서 요청
  • 웹 애플리케이션 서버(WAS)에서 HTTP 요청 메시지를 기반으로 request, response 생성
  • 해당 request, response를 서블릿 컨테이너에 전달 => service(request, response)
  • 서블릿 컨테이너에서 요청이 종료되면 response 객체 정보를 통해 HTTP 응답 생성
  • 웹 브라우저에 응답 반환
저작자표시

'Backend' 카테고리의 다른 글

[Spring] 스프링 컨테이너와 스프링 빈  (0) 2022.01.25
[Spring] HTTP 요청 파라미터 사용 - @RequestParam과 @ModelAttribue  (0) 2022.01.18
[Spring] MVC 패턴  (0) 2022.01.16
[Spring] MVC 패턴의 등장  (0) 2022.01.15
[Spring] HttpServletRequest와 HttpServletResponse 다루기  (0) 2022.01.11
    'Backend' 카테고리의 다른 글
    • [Spring] HTTP 요청 파라미터 사용 - @RequestParam과 @ModelAttribue
    • [Spring] MVC 패턴
    • [Spring] MVC 패턴의 등장
    • [Spring] HttpServletRequest와 HttpServletResponse 다루기
    pebblepark
    pebblepark
    프론트엔드 개발자입니다. 피드백은 언제나 환영입니다:)

    티스토리툴바