스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 5

Spring 정리 2021. 9. 27. 13:17

인프런 강의 23일차.

 - 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 1 (김영한 강사님)

 

1. Http요청 데이터 - 개요

 - HTTP 요청 메시지를 통해 클라이언트에서 서버로 데이터를 전달하는 방법

 - 주로 3가지의 방법으로 사용

 

1.1 GET - 쿼리 파라미터

 - /url=?username=hello&age=20

 - 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 표현해서 전달

 - 예) 검색, 필터, 페이징등에서 많이 사용하는 방식

 

1.2. POST - HTML form

 - content-type : application/x-www-form-urlencoded

 - 메시지 바디에 쿼리 파라미터 형식으로 전달, username=hello&age=20

 - 예) 회원가입, 상품주문, HTML Form 사용

 

1.3. HTTP message body에 데이터를 직접 담아서 요청

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

 - 데이터 형식은 주로 JSON 사용

 - POST, PUT, PATCH

 

2. HTTP 요청 데이터 - GET 쿼리 파라미터

 - 전달 데이터

   : username=hello

   : age=20

 - 메시지 바디 없이, URL의 '쿼리 파라미터'를 사용해서 데이터를 전달하다

  ex) 검색, 필터, 페이징등에서 많이 사용하는 방식

 - 쿼리 파라미터는 URL에 다음과 같이 '?' 를 시작으로 보낼 수 있다. 추가 파라미터는 '&'로 구분하면 된다.

 - http://localhost:8080/request-param?username=hello&age=20

 - 서버에서는 'HttpServletRequest'가 제공하는 메소드를 통해 쿼리 파라미터를 편리하게 조회할 수 있다.

 

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("[전체 파라미터 조회] - start");
        request.getParameterNames().asIterator()
                .forEachRemaining(paramName -> System.out.println(paramName + "=" + request.getParameter(paramName)));
        Enumeration<String> parameterNames = request.getParameterNames();
        System.out.println("[전체 파라미터 조회] - end");

        System.out.println("[단일 파라미터 조회] - start");
        //username=hello&age=20
        String username = request.getParameter("username");
        String age = request.getParameter("age");
        System.out.println("username = " + username);
        System.out.println("age = "+ age);
        System.out.println("[단일 파라미터 조회] - end");

        //username=hello&age=20&username=hello2
        System.out.println("[이름이 같은 복수 파라미터 조회] - start");
        String[] usernames = request.getParameterValues("username");
        for (String name : usernames) {
            System.out.println("username = "+name);
        }
        //아래와 같은 형태로 출력된다.
        //username = hello
        //username = hello2
        //만약 username에 2개 이상의 값이 할당된 상태에서 getParameter를 할 시 내부 우선순위에 의해 1개만 선택되어 표시된다.
        //다만, 중복으로 보내는 경우는 거의 없다.
        System.out.println("[이름이 같은 복수 파라미터 조회] - start");

    }

 

3. HTTP 요청 데이터 - POST HTML Form

 - 이번에는 HTML Form을 사용해서 클라이언트에서 서버로 데이터를 전송해보자.

 - 주로 회원가입, 상품 주문 등에서 사용하는 방식이다

 - content-type: 'application/x-www-form-urlencoded'

 - 메시지 바디에 쿼리 파라미터 형식으로 데이터를 전달한다. 'username=hello&age=20'

<!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>

 - 해당 form에서 submit 시 GET방식에서 사용한 메소드를 호출하는 것을 볼 수 있다.

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

 - 요청 URL : http://localhost:8080/request-param

 - content-type : application/x-www-form-urlencoded

 - message body : username=hello&age=20

 - application/x-www-form-urlencoded 형식은 앞서 GET에서 살펴본 쿼리 파라미터 형식과 같다. 따라서 '쿼리 파라미터 조회 메소드를 그대로 사용'하면 된다.

 - 클라이언트 입장에서는 두 방식에 차이가 있지만, 서버 입장에서는 둘의 형식이 동일하므로 request.getParameter()로 편리하게 구분 없이 조회할 수 있다.

 - 정리하면 request.getParameter()는 GET URL 쿼리 파라미터 형식도 지원하고, POST HTML Form 형식도 둘 다 지원한다.

 

 * 참고

 - content-type은 HTTP 메시지 바디의 데이터 형식을 지원한다.

 - GET URL 쿼리 파라미터 형식으로 클라이언트에서 서버로 데이터를 전달할 때는 HTTP 메시지 바디를 사용하지 않기 때문에 content-type이 없다.

 - POST HTML Form 형식으로 데이터를 전달하면 HTTP 메시지 바디에 해당 데이터를 포함해서 보내기 때문에 바디에 포함된 데이터가 어떤 형식인지 content-type을 꼭 지정해야 한다. 이렇게 폼으로 데이터를 전송하는 형식을 application/x-www-form-urlencoded라 한다.

 

 * postman을 사용한 테스트

 - 간단한 테스트에 html form을 만들기는 귀찮으므로 postman을 사용하여 테스트 수행.

 - POST 전송 시 body 및 Header가 x-www-form-urlencoded로 선택되었는지 확인!

 

4. HTTP 요청 데이터 - API 메시지 바디 - 단순 텍스트

 - Http message body에 데이터를 직접 담아서 요청

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

   : 데이터 형식은 주로 JSON 사용

   : POST, PUT, PATCH

 - 먼저 가장 단순한 텍스트 메시지를 HTTP 메시지 바디에 담아서 전송하고, 읽어보자

 - HTTP 메시지 바디의 데이터를 InputStream을 사용해서 직접 읽을 수 있다.

package hello.servlet.basic.request;

import org.springframework.util.StreamUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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");
    }
}

 - Postman을 사용하여 테스트해보자.

 

* 참고

 - inputStrream은 byte를 반환하므로 string으로 변환해줘야한다.

 - POST http://localhost:8080/request-body-string

 - content-type : text/plain

 - message-body : hello

 - 결과 : message-body : hello

 

5. HTTP 요청 데이터 - API 메시지 바디 - JSON

 - HTTP API에서 주로 사용하는 것은 JSON 형식

 

* JSON 형식 전송

 - POST http://localhost:8080/request-body-json

 - content-type : application/json

 - message-body : {"username" : "hello", "age" : 20}

 - 결과 : message-body : {"username" : "hello", "age" : 20}

 

* JSON 형식 파싱 추가

 - JSON형식으로 파싱할 수 있게 객체 생성

 - POST http://localhost:8080/request-body-json

 - content-type : application/json

 - message-body : {"username" : "hello", "age" : 20}

 - 결과 : message-body : {"username" : "hello", "age" : 20}

package hello.servlet.basic;

import lombok.Getter;
import lombok.Setter;

@Getter @Setter
public class HelloData {

    private String username;
    private int age;

    /*
    //프로젝트 세팅 때 Lombok 세팅을 해두었으므로 @Getter, @Setter 선언으로 아래 코드가 자동생성된다.
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
     */
}

 

package hello.servlet.basic.request;

import com.fasterxml.jackson.databind.ObjectMapper;
import hello.servlet.basic.HelloData;
import org.springframework.util.StreamUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

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

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

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

 

 

 

스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 4

Spring 정리 2021. 8. 30. 19:27

인프런 강의 22일차.

 - 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 1 (김영한 강사님)

 

1. HttpServletRequest의 역할

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

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

 - HTTP 요청 메시지 

    > POST /save HTTP/1.1

    > Host : localhost:8080

    > Content-type : application/www- x-form-urlencoded

    > username&age=40

 - START LINE

    > HTTP 메소드

    > URL

    > 쿼리 스트링

    > 스키마, 프로토콜

 - Header

    > Header 조회

 - Body

    > form 파라미터 형식 조회

    > message body 데이터 직접 조회

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

 - 임시 저장소 기능

    > 해당 HTTP 요청이 시작부터 끝날 때 까지 유지되는 임시 저장소 기능

    > 저장 : request.setAttribute(name, value)

    > 조회 : request.getAttribute(name)

 - 세션 관리 기능

    > request.getSession(create:true);

 - 중요 : HttpServletRequest, HttpServletResponse를 사용할 때 주의할 점은 이 객체들이 HTTP 요청 메시지, HTTP 응답 메시지를 편리하게 사용할 수 있도록 도와주는 객체라는 점이다. (따라서 이 기능에 대해 깊이있는 이해를 소장하려면 'HTTP 스펙이 제공하는 요청&응답 메시지 차를 이해애야 한다.

 

2. HttpServletRequest 기본 사용법

 - printStartLine(request) : header의 기본 정보들 표시

private void printStartLine(HttpServletRequest request) {
        System.out.println("--- REQUEST-LINE - start ---");
        System.out.println("request.getMethod() = " + request.getMethod()); //GET
        System.out.println("request.getProtocal() = " + 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-test
        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 - end ---");
        System.out.println();
    }

 - printHeader(reqeust) : header의 모든 내용 표시

//Header 모든 정보
    private void printHeader(HttpServletRequest request){
        System.out.println("--- Headers - Start ---");

        Enumeration<String> headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            System.out.println(headerName + " : " + headerName);
        }

        System.out.println("--- Headers - End ---");
    }

 - printHeaderUtils(request) : header의 정보를 간추려서 표시

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

- printEtc(request) : header의 기타 정보 표시

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

 

스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 3

Spring 정리 2021. 8. 25. 20:39

인프런 강의 21일차.

 - 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 1 (김영한 강사님)

 

* 스프링 시작

1. start.spring.io

 - 해당 옵션들을 선택해서 Generate

 

2. 프로젝트가 정상적으로 세팅되었는지 ServletApplication 실행

 

 - localhost:8080 접속 시 Whitelabel 오류 나오면 정상적으로 서버 실행 완료(아직 세팅한게 없으니 오류가 정상)

 

3. 환경설정 변경

 - 빌드 및 실행/테스트 실행 : Default가 Gradle로 되어있지만 IntelliJ IDEA로 실행하도록 변경

 

4. Lombok 라이브러리 설치

 - Lombok 라이브러리 설치

 

5. 어노테이션 프로세스 체크

 - 어노테이션 처리 활성화 체크해서 적용

 

 

6. Hello 서블릿

 - 스프링 부트 환경에서 서블릿을 등록하고 사용해보자.

  * 참고 : 서블릿은 톰캣 같은 웹 애플리케이션 서버를 직접 설치하고, 그 위에 서블릿 코드를 클래스 파일로 빌드해서 올린 다음, 톰캣 서버를 실행하면 된다. 하지만 이 과정은 매우 번거롭다. 스프링 부트는 톰캣 서버를 내장하고 있으므로, 톰캣 서버 설치 없이 편리하게 서블릿 코드를 실행할 수 있다.

 

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

 - @ServletComponentScan

    > 스프링 부트는 서블릿을 직접 등록해서 사용할 수 있도록 @ServletComponentScan을 지원한다.

//ServletApplication.java
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);
	}

}
//HelloServlet.java
package hello.servlet.basic;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;

@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
    
    @Override       //Ctrl + O 단축키를 통해 메소드 자동 구현
    public void service(ServletRequest request, ServletResponse 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);  //html body에 들어가는 내용
    }
}

 - @WebSevlet : 서블릿 애노테이션

    > name : 서블릿 이름

    > urlPatterns : URL 매핑

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

    > protected void service(HttpServletRequest request, HttpSevletResponse response)

 - 웹 브라우저 실행

    > http://localhost:8080/hello?userame=world

    > 결과 : hello world

 - 콘솔 실행 결과

    > HelloServlet.Service
    > request = org.apache.catalina.connector.RequestFacade@d7b5a2c
    > response = org.apache.catalina.connector.ResponseFacade@15c00532
    > username = world

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

    > 다음 파일에 설정 추가 (resources/application.properties)

    > logging.level.org.apache.coyote.http11=debug 추가 시 HTTP req, res 내용을 전부 볼 수 있다.

  * 운영서버에 모든 로그를 남길 시 성능저하가 될 수 있으니 참고.

 

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

 - 스프링부트가 내장 톰캣 서버를 생성한다.

 - 내장 톰캣 서버가 서블릿 컨테이너를 통해 서블릿을 생성한다.

 - 웹 브라우저가 HTTP 요청.

 - HTTP 요청 메시지를 기반으로 WAS가 request, response 객체를 생성해서 싱글톤으로 떠있는 서블릿을 호출함

 - 서블릿이 종료되면 Response 객체 정보를 WAS에 전달

 - WAS는 전달된 Response 객체 정보로 HTTP 응답 메시지를 생성함.

 - 참고 : HTTP 응답에서 Content-Length는 WAS가 자동으로 생성해준다.