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

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

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

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
pebblepark
Backend

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

[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
프론트엔드 개발자입니다. 피드백은 언제나 환영입니다:)

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.