[스프링 MVC 1편] 2. 서블릿

2024. 1. 25. 00:23·인프런 Spring 강의 정리/스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술
728x90
반응형

📌 프로젝트 생성

✔ 개발 환경

  • Java 17
  • IntelliJ IDEA

✔ 스프링 부트 스타터 사이트에서 프로젝트 생성
스프링 부트 스타터

  • 프로젝트 선택
    • Project : Gradle-Groovy Project
    • Language : Java
    • Spring boot 3.2.1
  • Project Metadata
    • Group : hello
    • Artifact : servlet
    • Name : servelt
    • Package name : hello.servlet
    • Packing : War(주의) (JSP를 실행하기 위해서 필요)
    • Java 17

 

🔶build.gradle

plugins {
    id 'java'
    id 'war'
    id 'org.springframework.boot' version '3.2.1'
    id 'io.spring.dependency-management' version '1.1.4'
}

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

java {
    sourceCompatibility = '17'
}

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'
}

tasks.named('test') {
    useJUnitPlatform()
}
  • 동작 확인
    • 기본 메인 클래스 실행(ServletApplication.main())
    • http://localhost:8080 호출해서 Whitelabel Error Page가 나오면 정상 동작

스프링 부트 3.2 부터 Gradle 옵션을 선택하자.

  • Preferences ➡ Build, Execution, Deployment ➡ Build Tools ➡ Gradle
    • Build and run using: Gradle
    • Run tests using: Gradle

 

 

 

✔ 롬복 적용

  1. Preferences -> plugin -> lombok 검색 실행 (재시작)
  2. Preferences -> Annotation Processors 검색
    -> Enable annotation processing 체크 (재시작)
  3. 임의의 테스트 클래스를 만들고 @Getter, @Setter 확인

✔ Postman을 설치
설치 링크

 

 

📌 Hello 서블릿

⚡ 서블릿

  • 톰캣 같은 웹 애플리케이션 서버를 직접 설치하고, 그 위에 서블릿 코드를 클래스 파일로 빌드해서 올림
    • 톰캣 서버를 실행
    • 매우 번거로움
  • 스프링 부트는 톰캣 서버를 내장하고 있으므로, 톰캣 서버 설치 없이 편리하게 서블릿 코드를 실행할 수 있음

 

 

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

@ServletComponentScan
➡ 서블릿을 직접 등록해서 사용

 

🔶 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 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;

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

✔ @WebServlet : 서블릿 애노테이션

  • name : 서블릿 이름
  • urlPatterns : URL 매핑

 

✔ HTTP 요청을 통해 매핑된 URL이 호출되면 서블릿 컨테이너는 다음 메서드를 실행

protected void service(HttpServletRequest request, HttpServletResponse response)

 

 

✔ 웹 브라우저 실행

  • http://localhost:8080/hello?username=world
  • 결과 : hello world

 

✔ 콘솔 실행 결과

HelloServlet.service
request = org.apache.catalina.connector.RequestFacade@5e4e72
response = org.apache.catalina.connector.ResponseFacade@37d112b6
username = world

 

 

 

⚡ HTTP 요청 메시지 로그로 확인하기

🔶 application.yml

logging:
  level:
    org:
      apache:
        coyote:
          http11: debug

➡ 서버를 다시 시작하고, 요청해보면 서버가 받은 HTTP 요청 메시지를 출력하는 것을 확인

...o.a.coyote.http11.Http11InputBuffer: Received [GET /hello?username=servlet
 HTTP/1.1
 Host: localhost:8080
 Connection: keep-alive
 Cache-Control: max-age=0
 sec-ch-ua: "Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"
 sec-ch-ua-mobile: ?0
 Upgrade-Insecure-Requests: 1
 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_1) AppleWebKit/537.36
 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/
webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: http://localhost:8080/basic.html
Accept-Encoding: gzip, deflate, br
Accept-Language: ko,en-US;q=0.9,en;q=0.8,ko-KR;q=0.7
]

운영서버에 이렇게 모든 요청 정보를 다 남기면 성능저하가 발생할 수 있으므로 개발 단계에서만 적용

 

 

 

⚡ 서블릿 컨테이너 동작 방식 설명

✔ 내장 톰캣 서버 생성

 

 

✔ HTTP 요청, HTTP 응답 메시지

✔ 웹 애플리케이션 서버의 요청 응답 구조

HTTP 응답에서 Content-Length는 웹 애플리케이션 서버가 자동으로 생성해줌

 

 

 

⚡ welcome 페이지 추가

🔶 main/webapp/index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body> <ul>
    <li><a href="basic.html">서블릿 basic</a></li> </ul>
</body>
</html>

 

 

🔶 main/webapp/basic.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body> <ul>
    <li>hello 서블릿 <ul>
        <li><a href="/hello?username=servlet">hello 서블릿 호출</a></li> </ul>
    </li>
    <li>HttpServletRequest
        <ul>
            <li><a href="/request-header">기본 사용법, Header 조회</a></li> <li>HTTP 요청 메시지 바디 조회
            파라미터</a></li> li>
            <ul>
                <li><a href="/request-param?username=hello&age=20">GET - 쿼리
                    <li><a href="/basic/hello-form.html">POST - HTML Form</a></
                    <li>HTTP API - MessageBody -> Postman 테스트</li> </ul>
    </li> </ul>
</li>
<li>HttpServletResponse
    <ul>
        <li><a href="/response-header">기본 사용법, Header 조회</a></li> <li>HTTP 응답 메시지 바디 조회
        <ul>
            <li><a href="/response-html">HTML 응답</a></li>
            <li><a href="/response-json">HTTP API JSON 응답</a></li>
        </ul> </li>
    </ul> </li>
</ul>
</body>
</html>

 

 

 

📌 HttpServletRequest

⚡ 개요

✔ HttpServletRequest 역할

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

 

✔ HTTP 요청 메시지

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

username=kim&age=20
  • START LINE
    • HTTP 메소드
    • URL
    • 쿼리 스트링
    • 스키마, 프로토콜
  • header
    • 헤더 조회
  • body
    • form 파라미터 형식 조회
    • message body 데이터 직접 조회

 

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

✔ 임시 저장소 기능

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

✔ 세션 관리 기능

  • request.getSesson(create: true)

 

 

✔중요

  • HttpServletRequest, HttpServletResponse : HTTP 요청 메시지, HTTP 응답 메시지를 편리하게 사용하도록 도와주는 객체
  • 이 기능에 대해 깊이있는 이해를 하려면 HTTP 스펙이 제공하는 요청, 응답 메시지 자체를 이해해야 함

 

 

⚡ 기본 사용법

🔶 hello.servlet.basic.request.RequestHeaderServlet

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

import java.io.IOException;

//http://localhost:8080/request-header?username=hello
@WebServlet(name = "requestHeaderServlet", urlPatterns = "/request-header")
public class RequestHeaderServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        printStartLine(request);
        printHeaders(request);
        printHeaderUtils(request);
        printEtc(request);

        response.getWriter().write("ok");

    }
}

 

 

✔ start-line 정보

 //start line 정보
    private void printStartLine(HttpServletRequest request) {
        System.out.println("--- REQUEST-LINE - start ---");
        System.out.println("request.getMethod() = " + request.getMethod()); //GET
        System.out.println("request.getProtocol() = " + request.getProtocol()); //HTTP/1.1
        System.out.println("request.getScheme() = " + request.getScheme()); //http
        // http://localhost:8080/request-header
        System.out.println("request.getRequestURL() = " + request.getRequestURL());
        // /request-header
        System.out.println("request.getRequestURI() = " + request.getRequestURI());
        //username=hi
        System.out.println("request.getQueryString() = " +
                request.getQueryString());
        System.out.println("request.isSecure() = " + request.isSecure()); //https 사용유무
        System.out.println();
    }

 

결과

 --- REQUEST-LINE - start ---
 request.getMethod() = GET
  request.getProtocol() = HTTP/1.1
 request.getScheme() = http
 request.getRequestURL() = http://localhost:8080/request-header
 request.getRequestURI() = /request-header
 request.getQueryString() = username=hello
 request.isSecure() = false
 --- REQUEST-LINE - end ---

 

 

✔ 헤더 정보

 //Header 모든 정보
    private void printHeaders(HttpServletRequest request) {
        System.out.println("--- Headers - start ---");
     /*
         Enumeration<String> headerNames = request.getHeaderNames();
         while (headerNames.hasMoreElements()) {
             String headerName = headerNames.nextElement();
             System.out.println(headerName + ": " + request.getHeader(headerName));
         }
    */
        request.getHeaderNames().asIterator()
                .forEachRemaining(headerName -> System.out.println(headerName + ": " + request.getHeader(headerName)));
        System.out.println("--- Headers - end ---");
        System.out.println();
    }

 

결과

--- Headers - start ---
 host: localhost:8080
 connection: keep-alive
 cache-control: max-age=0
 sec-ch-ua: "Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"
 sec-ch-ua-mobile: ?0
 upgrade-insecure-requests: 1
 user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_0) AppleWebKit/537.36
 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36
 accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/
 webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
  sec-fetch-site: none
 sec-fetch-mode: navigate
 sec-fetch-user: ?1
 sec-fetch-dest: document
 accept-encoding: gzip, deflate, br
 accept-language: ko,en-US;q=0.9,en;q=0.8,ko-KR;q=0.7
 --- Headers - end ---

 

 

 

✔ 헤더 정보

//Header 편리한 조회
    private void printHeaderUtils(HttpServletRequest request) {
        System.out.println("--- Header 편의 조회 start ---");
        System.out.println("[Host 편의 조회]");
        System.out.println("request.getServerName() = " + request.getServerName()); //Host 헤더
        System.out.println("request.getServerPort() = " + request.getServerPort()); //Host 헤더
        System.out.println();

        System.out.println("[Accept-Language 편의 조회]");
        request.getLocales().asIterator()
                .forEachRemaining(locale -> System.out.println("locale = " + locale));
        System.out.println("request.getLocale() = " + request.getLocale());
        System.out.println();

        System.out.println("[cookie 편의 조회]");
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                System.out.println(cookie.getName() + ": " + cookie.getValue());
            }
        }
        System.out.println();

        System.out.println("[Content 편의 조회]");
        System.out.println("request.getContentType() = " + request.getContentType());
        System.out.println("request.getContentLength() = " + request.getContentLength());
        System.out.println("request.getCharacterEncoding() = " + request.getCharacterEncoding());
        System.out.println("--- Header 편의 조회 end ---");
        System.out.println();
    }

 

결과

--- Header 편의 조회 start ---
[Host 편의 조회] request.getServerName() = localhost request.getServerPort() = 8080
[Accept-Language 편의 조회] locale = ko
locale = en_US
locale = en
 locale = ko_KR
 request.getLocale() = ko
[cookie 편의 조회]
[Content 편의 조회] request.getContentType() = null request.getContentLength() = -1 request.getCharacterEncoding() = UTF-8 --- Header 편의 조회 end ---

 

 

✔ 기타 정보

//기타 정보
    private void printEtc(HttpServletRequest request) {
        System.out.println("--- 기타 조회 start ---");
        System.out.println("[Remote 정보]");
        System.out.println("request.getRemoteHost() = " +
                request.getRemoteHost()); //
        System.out.println("request.getRemoteAddr() = " +
                request.getRemoteAddr()); //
        System.out.println("request.getRemotePort() = " +
                request.getRemotePort()); //
        System.out.println();
        System.out.println("[Local 정보]");
        System.out.println("request.getLocalName() = " + request.getLocalName()); // System.out.println("request.getLocalAddr() = " + request.getLocalAddr()); // System.out.println("request.getLocalPort() = " + request.getLocalPort()); //
        System.out.println("--- 기타 조회 end ---");
        System.out.println();
    }

 

결과

--- 기타 조회 start ---
[Remote 정보]
request.getRemoteHost() = 0:0:0:0:0:0:0:1 request.getRemoteAddr() = 0:0:0:0:0:0:0:1 request.getRemotePort() = 54305
[Local 정보]
 request.getLocalName() = localhost
 request.getLocalAddr() = 0:0:0:0:0:0:0:1
 request.getLocalPort() = 8080
--- 기타 조회 end ---

cf)
로컬에서 테스트하면 IPv6 정보가 나오는데 IPv4 정보를 보고싶으면, 다음 옵션을 VM options에 넣어주면 됨
➡ Djava.net.preferIPv4Stack=true

 

 

 

📌 HTTP 요청 데이터

⚡ 개요

✔ 대표적인 3가지 방법

✔ GET - 쿼리 파라미터

  • /url**?username=hello&age=20**
  • 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함해서 전달
  • ex) 검색, 필터, 페이징 등에서 많이 사용하는 방식

✔ POST - HTML Form

  • content-type: application/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파라미터 형식으로 전달 username=hello&age=20
  • ex) 회원가입, 상품 주문, HTML Form 사용

✔ HTTP message body에 데이터 직접 담아서 요청

  • HTTP API에서 주로 사용, JSON, XML, TEXT

❗  데이터 형식은 주로 JSON에서 다룸

 

 

 

⚡ GET 쿼리 파라미터

➡ 다음 데이터를 클라이언트에서 서버로 전송

  • 전달 데이터
    •  username=hello
    • age=20
  • 메시지 바디 없이, URL의 쿼리 파라미터를 사용해서 데이터를 전달
  • ex) 검색, 필터, 페이징 등에서 많이 사용하는 방식
  • 쿼리 파라미터는 URL에 다음과 같이 ? 를 시작으로 보낼 수 있음
  • 추가 파라미터는 & 로 구분

실행 링크 : http://localhost:8080/request-param?username=hello&age=20

 

 

 

✔ 쿼리 파라미터 조회 메서드

String username = request.getParameter("username"); //단일 파라미터 조회
Enumeration<String> parameterNames = request.getParameterNames(); //파라미터 이름들
모두 조회
Map<String, String[]> parameterMap = request.getParameterMap(); //파라미터를 Map으로
조회
String[] usernames = request.getParameterValues("username"); //복수 파라미터 조회

 

 

🔶 RequestParamServlet

package hello.servlet.basic.request;

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;

/**
 * 1. 파라미터 전송 가능
 * http://localhost:8080/request-param?username=hello&age=20
 * <p>
 * 2. 동일한 파라미터 전송 가능
 * http://localhost:8080/request-param?username=hello&username=kim&age=20
 */
@WebServlet(name = "requestParamServlet", urlPatterns = "/request-param")
public class RequestParamServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        System.out.println("[전체 파라미터 조회] - start");
        /*
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            System.out.println(paramName + "=" +
request.getParameter(paramName));
} */
        request.getParameterNames().asIterator()
                .forEachRemaining(paramName -> System.out.println(paramName +
                        "=" + request.getParameter(paramName))); System.out.println("[전체 파라미터 조회] - end"); System.out.println();
        System.out.println("[단일 파라미터 조회]");
        String username = request.getParameter("username"); System.out.println("request.getParameter(username) = " + username);
        String age = request.getParameter("age");
        System.out.println("request.getParameter(age) = " + age);
        System.out.println();
        System.out.println("[이름이 같은 복수 파라미터 조회]"); System.out.println("request.getParameterValues(username)"); String[] usernames = request.getParameterValues("username"); for (String name : usernames) {
            System.out.println("username=" + name);
        }
        response.getWriter().write("ok");
    }
}

 

 

실행 - 파라미터 전송

실행 링크 : http://localhost:8080/request-param?username=hello&age=20

 

결과

[전체 파라미터 조회] - start username=hello
age=20
[전체 파라미터 조회] - end
[단일 파라미터 조회] request.getParameter(username) = hello request.getParameter(age) = 20
[이름이 같은 복수 파라미터 조회]
 request.getParameterValues(username)
 username=hello

 

 

실행 - 동일 파라미터 전송
실행 링크 : http://localhost:8080/request-param?username=hello&username=kim&age=20

 

결과

[전체 파라미터 조회] - start username=hello
age=20
[전체 파라미터 조회] - end
[단일 파라미터 조회] request.getParameter(username) = hello request.getParameter(age) = 20
[이름이 같은 복수 파라미터 조회] request.getParameterValues(username) username=hello
username=kim

 

복수 파라미터에서 단일 파라미터 조회

  • username=hello&username=kim 과 같이 파라미터 이름은 하나인데, 값이 중복이면
    • request.getParameter()는 하나의 파라미터 이름에 대해서 단 하나의 값만 있을 때 사용해야함 ➡ 첫번째 값을 반환
    • 지금처럼 중복이라면 request.getValues() 사용
  •  

 

⚡ POST HTML Form

  • HTML의 Form을 사용해서 클라이언트에서 서버로 데이터를 전송
    (회원 가입, 상품 주문 등에서 사용하는 방식)

✔ 특징

  • content-type: application/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파라미터 형식으로 데이터를 전달
    • username=hello&age=20

 

🔶 src/main/webapp/basic/hello-form.html

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>Title</title>
 </head>
 <body>
 <form action="/request-param" method="post">
username: <input type="text" name="username" /> age: <input type="text" name="age" /> <button type="submit">전송</button>
</form>
</body>
</html>

 

실행
http://localhost:8080/basic/hello-form.html

주의❗
웹 브라우저가 결과를 캐시하고 있어서, 과거에 작성했던 html 결과가 보이는 경우도 있음
➡ 웹 브라우저의 새로고침을 직접 선택해주면 됨
➡ 서버를 재시작하지 않아서 그럴 수도 있음

 

 

POST의 HTML Form을 전송하면 웹 브라우저는 다음 형식으로 HTTP 메시지를 만든다. (웹 브라우저 개발자 모드 확인)

  • 요청 URL : http://localhost:8080/request-param
  • content-type : application/x-www-form-urlencoded
    • GET에서 쿼리 파라미터 형식과 같음
  • 쿼리 파라미터 조회 메서드를 그대로 사용하면 됨
  • 클라이언트(웹 브라우저) 입장에서는 두 방식에 차이가 있지만, 서버 입장에서는 둘의 형식이 동일하므로, request.getParameter() 로 편리하게 구분없이 조회하면 됨
  • message body : username=hello&age=20

 

  •  

cf)

  • content-type은 HTTP 메시지 바디의 데이터 형식을 지정
  • GET URL 쿼리 파라미터 형식으로 클라이언트에서 서버로 데이터를 전달할 때는 HTTP 메시지 바디를 사용하지 않기 때문에 content-type이 없음
  • POST HTML Form 형식으로 데이터를 전달하면 HTTP 메시지 바디에 해당 데이터를 포함해서 보내기 때문에 바디에 포함된 데이터가 어떤 형식인지 content-type을 꼭 지정해야 함
  • 폼으로 데이터를 전송하는 형식을 application/x-www-form-urlencoded라고 함

 

✔ Postman을 사용한 테스트

  • Postman 테스트 주의사항 POST 전송시
    • Body x-www-form-urlencoded 선택
    • Headers에서 content-type: application/x-www-form-urlencoded 로 지정된 부분 꼭 확인

 

 

⚡ API 메시지 바디

✔ 단순 텍스트

  • HTTP message body에 데이터를 직접 담아서 요청
    • HTTP API에서 주로 사용, JSON, XML, TEXT
    • 데이터 형식은 주로 JSON 사용
    • POST, PUT, PATCH
  • HTTP 메시지 바디의 데이터를 InputStream을 사용해서 직접 읽을 수 있음

 

🔶 RequestBodyStringServlet

package hello.servlet.basic.request;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-body- string")
public class RequestBodyStringServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        System.out.println("messageBody = "+ messageBody);

        response.getWriter().write("ok");
    }
}

cf)
inputStream은 byte코드를 반환 ➡ String으로 변환하려면 문자표(Charset)을 지정해야 함
ex) UTF_8 Charset

 

문자 전송

  • POST http://localhost:8080/request-body-string
  • content-type: text/plain
  • message body: hello
  • 결과: messageBody = hello

 

 

⚡ JSON

✔ JSON 형식 전송

  • POST http://localhost:8080/request-body-json
  • content-type: application/json
  • message body: {"username": "hello", "age": 20}
  • 결과: messageBody = {"username": "hello", "age": 20}

 

✔ JSON 형식 파싱 추가

🔶 HelloData

package hello.servlet.basic;

import lombok.Getter;
import lombok.Setter;

@Getter @Setter
public class HelloData {

    private String username;
    private int age;
}

 

 

🔶 hello.servlet.basic.request/RequestBodyJsonServlet

package hello.servlet.basic.request;

import com.fasterxml.jackson.databind.ObjectMapper;
import hello.servlet.basic.HelloData;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * http://localhost:8080/request-body-json
 *
 * JSON 형식 전송
 * content=type: application/json
 * message body: {"username": "hello", "age": 20}
 *
 */
@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json")
public class RequestBodyJsonServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        System.out.println("messageBody = " + messageBody);
        HelloData helloData = objectMapper.readValue(messageBody,
                HelloData.class);
        System.out.println("helloData.username = " + helloData.getUsername());
        System.out.println("helloData.age = " + helloData.getAge());
        response.getWriter().write("ok");
    }
}

 

✔ Postman으로 실행

  • POST http://localhost:8080/request-body-json
  • content-type: application/json (Body raw, 가장 오른쪽에서 JSON 선택)
  • message body: {"username": "hello", "age": 20}

 

출력결과

 messageBody={"username": "hello", "age": 20}
 data.username=hello
data.age=20

cf)

  • JSON 결과를 파싱해서 사용할 수 있는 자바 객체로 변환하려면 Jackson, Gson같은 JSON 변환 라이브러리를 추가해서 사용해야 함
  • 스프링 부트로 Spring MVC를 선택하면 기본으로 Jackson 라이브러리(ObjectMapper)를 함께 제공

 

cf)
HTML form 데이터도 메시지 바디를 통해 전송되므로 직접 읽을 수 있음
➡ 하지만 편리한 파라미터 조회 기능(request.getParameter(..))을 이미 제공하기 때문에 파라미터 조회 기능 사용하면 됨

 

📌 HttpServletResponse

⚡ 기본 사용법

✔ HTTP 응답메시지 생성

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

✔ 편의 기능 제공

  • Content-Type, 쿠키, Redirect

 

🔶 hello.servlet.basic.response.ResponseHeaderServlet

package hello.servlet.basic.response;

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

import java.io.IOException;
import java.io.PrintWriter;

/**
 * http://localhost:8080/response-header
 *
 */
@WebServlet(name = "responseHeaderServlet", urlPatterns = "/response-header")
public class ResponseHeaderServlet extends HttpServlet {

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

        //[status-line]
        response.setStatus(HttpServletResponse.SC_OK); //200

        //[response-headers]
        response.setHeader("Content-Type", "text/plain;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must- revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("my-header","hello");

        //[Header 편의 메서드]
        content(response);
        cookie(response);
        redirect(response);

        //[message body]
        PrintWriter writer = response.getWriter();
        writer.println("ok");
    }

    //Content 편의 메서드
    private void content(HttpServletResponse response) {
        //Content-Type: text/plain;charset=utf-8
        //Content-Length: 2
        //response.setHeader("Content-Type", "text/plain;charset=utf-8");

        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
        //response.setContentLength(2); //(생략시 자동 생성)
    }

    //쿠키 편의 메서드
    private void cookie(HttpServletResponse response) {
        //Set-Cookie: myCookie=good; Max-Age=600;
        // response.setHeader("Set-Cookie", "myCookie=good; Max-Age=600");
        Cookie cookie = new Cookie("myCookie", "good");
        cookie.setMaxAge(600); //600초
        response.addCookie(cookie);
    }

    //redirect 편의 메서드
    private void redirect(HttpServletResponse response) throws IOException {
        //Status Code 302
        //Location: /basic/hello-form.html

        //response.setStatus(HttpServletResponse.SC_FOUND); //302
        //response.setHeader("Location", "/basic/hello-form.html");
        response.sendRedirect("/basic/hello-form.html");
    }

}

 

 

📌 HTTP 응답 데이터

  • 단순 텍스트 응답
    • 앞에서 살펴봄(write.print("ok"))
  • HTML응답
  • HTTP API: MessageBody JSON응답

 

⚡ 단순 텍스트, HTMl

🔶 hello.servlet.web.response.ResponseHtmlServlet

package hello.servlet.basic.response;

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;
import java.io.PrintWriter;

@WebServlet(name = "responseHtmlServlet", urlPatterns = "/response-html")
public class ResponseHtmlServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse
            response)
            throws ServletException, IOException {
        //Content-Type: text/html;charset=utf-8
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<html>");
        writer.println("<body>");
        writer.println(" <div>안녕?</div>");
        writer.println("</body>");
        writer.println("</html>");
    }답
}

➡ HTTP 응답으로 HTML을 반환할 때는 content-type을 text/html로 지정해야 함

 

실행

  • http://localhost:8080/response-html
  • 페이지 소스보기를 사용하면 결과 HTML을 확인할 수 있다.

 

 

⚡ API JSON

🔶 hello.servlet.web.response.ResponseHtmlServlet

package hello.servlet.basic.response;

import com.fasterxml.jackson.databind.ObjectMapper;
import hello.servlet.basic.HelloData;
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;

/**
 * http://localhost:8080/response-json
 *
 */
@WebServlet(name = "responseJsonServlet", urlPatterns = "/response-json")
public class ResponseJsonServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse
            response)
            throws ServletException, IOException {
        //Content-Type: application/json
        response.setHeader("content-type", "application/json");
        response.setCharacterEncoding("utf-8");
        HelloData data = new HelloData();
        data.setUsername("kim");
        data.setAge(20);
        //{"username":"kim","age":20}
        String result = objectMapper.writeValueAsString(data);
        response.getWriter().write(result);
    }
}
  • HTTP 응답으로 JSON을 반환할 때는 content-type을 application/json로 지정해야 함
  • Jackson 라이브러리가 제공하는 objectMapper.writeValueAsString()를 사용하면 객체를 JSON문자로 변경할 수 있음
  • response.getWriter()를 사용하면 추가 파라미터를 자동으로 추가
    • response.getOutputStream()으로 출력하면 그런 문제가 없음

실행

  • http://localhost:8080/response-json

cf)
application/json 은 스펙상 utf-8 형식을 사용하도록 정의되어 있음
➡  charset=utf-8과 같은 추가 파라미터를 지원하지 않음
➡  따라서 application/json 이라고만 사용해야지 application/json;charset=utf-8 이라고 전달하는 것은 의미 없는 파라미터를 추가한 것

 

 

 

 

<스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술_김영한>을 수강하고 작성한 글입니다

 

 

 


PREV

 

[스프링 MVC 1편] 1. 웹 애플리케이션 이해

📌 웹 서버, 웹 애플리케이션 서버 ⚡ 웹 - HTTP 기반 ✔ 웹 : HTTP 프로토콜을 기반으로 통신 ⚡ 모든 것이 HTTP HTTP 메시지에 모든 것을 전송 HTML, TEXT IMAGE, 음성, 영상, 파일 JSON, XML (API) 거의 모든 형

nyeroni.tistory.com

NEXT

 

[스프링 MVC 1편] 3. 서블릿, JSP, MVC 패턴

📌 회원 관리 웹 애플리케이션 요구사항 ✔ 회원 정보 이름 : username 나이 : age ✔ 기능 요구사항 회원 저장 회원 목록 조회 ⚡ 회원 도메인 모델 🔶 hello.servlet.domain.member.Member package hello.servlet.dom

nyeroni.tistory.com

 

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'인프런 Spring 강의 정리 > 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술' 카테고리의 다른 글

[스프링 MVC 1편] 6. 스프링 MVC - 기본 기능  (0) 2024.01.25
[스프링 MVC 1편] 5. 스프링 MVC - 구조 이해  (1) 2024.01.25
[스프링 MVC 1편] 4. MVC 프레임워크 만들기  (0) 2024.01.25
[스프링 MVC 1편] 3. 서블릿, JSP, MVC 패턴  (1) 2024.01.25
[스프링 MVC 1편] 1. 웹 애플리케이션 이해  (0) 2024.01.24
'인프런 Spring 강의 정리/스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술' 카테고리의 다른 글
  • [스프링 MVC 1편] 5. 스프링 MVC - 구조 이해
  • [스프링 MVC 1편] 4. MVC 프레임워크 만들기
  • [스프링 MVC 1편] 3. 서블릿, JSP, MVC 패턴
  • [스프링 MVC 1편] 1. 웹 애플리케이션 이해
예롱메롱
예롱메롱
  • 예롱메롱
    예롱이의 개발 블로그
    예롱메롱
  • 전체
    오늘
    어제
    • 전체보기 (274)
      • 프로젝트 (35)
        • Wedle (12)
        • 인스타그램 클론 코딩 (13)
        • 스프링 부트와 AWS로 혼자 구현하는 웹 서비스 (10)
      • 인프런 Spring 강의 정리 (79)
        • 스프링 입문 - 코드로 배우는 스프링 부트, 웹 .. (7)
        • Spring 핵심 원리 - 기본편 (9)
        • 모든 개발자를 위한 HTTP 웹 기본 지식 (8)
        • 자바 ORM 표준 JPA 프로그래밍 - 기본편 (11)
        • 실전! 스프링 부트와 JPA 활용1 - 웹 애플리.. (6)
        • 실전! 스프링 부트와 JPA 활용2 - API 개.. (5)
        • 실전! 스프링 데이터 JPA (7)
        • 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 (7)
        • 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 (11)
        • 실전! Querydsl (8)
      • Cloud (3)
      • Spring (6)
        • spring boot (5)
        • 소셜로그인 (1)
      • Docker (2)
      • DevOps (0)
      • Coding Test (114)
        • Programmers (37)
        • Baekjoon (76)
      • KB It's Your Life 6기 (1)
      • CS (18)
        • 알고리즘 (13)
        • 컴퓨터 구조 (1)
        • Operating System (0)
        • Network (0)
        • Database (4)
      • git (1)
      • Language (15)
        • Java (5)
        • C++ (6)
        • Python (4)
    • GITHUB GITHUB
    • INSTAGRAM INSTAGRAM
  • hELLO· Designed By정상우.v4.10.3
예롱메롱
[스프링 MVC 1편] 2. 서블릿
상단으로

티스토리툴바