반응형

# 스프링 MVC 웹 페이지 만들기

## 프로젝트 생성.

  • Dependencies : Spring Web, Thymeleaf, Lombok
  • GENERATE 클릭 후 압축 해제 진행. 인텔리제이에서 File > open 클릭 후 압축해제한 폴더 내 build.gradle 선택하여 파일 열기.
  • Lombok : File > Settings > annotation processors 입력 후 Enable annotation processing 체크.
  • Gradle : File > Settings > Gradle 검색 후 Gradle에서 아래와 같이 설정.
Build and run using : IntelliJ IDEA
Run tests using : IntelliJ IDEA
  • 전체적인 설정 완료 후 main 실행해서 정상 작동하는지 확인.
  • Port 충돌날 경우 Run > Edit Configurations > Environment variables 에 아래와 같이 입력하여 Port 변경.
server.port=8082
 
  • 웰컴 페이지 추가 : resources > static에 index.html 추가.
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    <li>상품 관리
        <ul>
            <li><a href="/basic/items">상품 관리 - 기본</a></li>
        </ul>
    </li>
</ul>
</body>
</html>

## 요구사항 분석

  • 상품 도메인 모델 : 상품 ID, 상품명, 가격, 수량,
  • 상품 관리 기능 : 상품 목록, 상품 상세, 상품 등록, 상품 수정
  • 필요 화면 : 상품 목록, 상품 상세, 상품 등록 폼, 상품 수정 폼

서비스 제공 흐름

## 상품 도메인 개발

item 상품 객체 생성.

package hello.itemservice.domain.item;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

//@Getter @Setter
@Data
public class Item {

    private Long id;
    private String itemName;
    private Integer price;
    private Integer quantity;

    public Item() {
    }

    public Item(String itemName, Integer price, Integer quantity) {
        this.itemName = itemName;
        this.price = price;
        this.quantity = quantity;
    }
}
  • @Data 의 경우 주의해서 사용 가능하면 @Getter, @Setter 사용.

ItemRepository 상품 저장소.

package hello.itemservice.domain.item;

import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class ItemRepository {

    // 실무에서는 동시 접근과 관련하여 HashMap 보다는 ConcurrentHashMap사용.
    private static final Map<Long, Item> store = new HashMap<>();   // static
    private static long sequence = 0L;  // static

    public Item save(Item item) {
        item.setId(++sequence);
        store.put(item.getId(), item);

        return item;
    }

    public Item findById(Long id) {
        return store.get(id);
    }

    public List<Item> findAll() {
        return new ArrayList<>(store.values());
    }

    public void update(Long itemId, Item updateParam) {
        Item findItem = findById(itemId);
        findItem.setItemName(updateParam.getItemName());
        findItem.setPrice(updateParam.getPrice());
        findItem.setQuantity(updateParam.getQuantity());
    }

    public void clearStore() {
        store.clear();
    }
}

ItemRepositoryTest.

package hello.itemservice.domain.item;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class ItemRepositoryTest {

    ItemRepository itemRepository = new ItemRepository();

    @AfterEach
    void afterEach() {
        itemRepository.clearStore();
    }

    @Test
    void save() {
        // given
        Item item = new Item("itemA", 10000, 10);

        // when
        Item saveItem = itemRepository.save(item);

        // then
        Item findItem = itemRepository.findById(item.getId());
        assertThat(findItem).isEqualTo(saveItem);
    }

    @Test
    void findAll() {
        // given
        Item item1 = new Item("item1", 10000, 10);
        Item item2 = new Item("item2", 20000, 50);
        itemRepository.save(item1);
        itemRepository.save(item2);

        // when
        List<Item> result = itemRepository.findAll();

        // then
        assertThat(result.size()).isEqualTo(2);
        assertThat(result).contains(item1, item2);
    }

    @Test
    void updateItem() {
        // given
        Item item = new Item("item1", 10000, 10);

        Item savedItem = itemRepository.save(item);
        Long itemId = savedItem.getId();

        // when
        Item updateParam = new Item("item2", 20000, 30);
        itemRepository.update(itemId, updateParam);

        // then
        Item findItem = itemRepository.findById(itemId);
        assertThat(findItem.getItemName()).isEqualTo(updateParam.getItemName());
        assertThat(findItem.getPrice()).isEqualTo(updateParam.getPrice());
        assertThat(findItem.getQuantity()).isEqualTo(updateParam.getQuantity());
    }
}

## 상품 서비스 HTML

부트스트랩 

 

Bootstrap

The most popular HTML, CSS, and JS library in the world.

getbootstrap.com

 

Download

Download Bootstrap to get the compiled CSS and JavaScript, source code, or include it with your favorite package managers like npm, RubyGems, and more.

getbootstrap.com

이동: https://getbootstrap.com/docs/5.0/getting-started/download/
Compiled CSS and JS 항목을 다운로드.

압축 출고 bootstrap.min.css 를 복사해 아래 폴더에 추가.
resources/static/css/bootstrap.min.css

HTML, CSS

  • /resources/static/css/bootstrap.min.css 부트스트랩 다운로드해서 추가.
  • /resources/static/html/items.html
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <link href="../css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="max-width: 600px">
    <div class="py-5 text-center">
        <h2>상품 목록</h2>
    </div>
    <div class="row">
        <div class="col">
            <button class="btn btn-primary float-end"
                    onclick="location.href='addForm.html'" type="button">상품
                등록</button>
        </div>
    </div>
    <hr class="my-4">
    <div>
        <table class="table">
            <thead>
            <tr>
                <th>ID</th>
                <th>상품명</th>
                <th>가격</th>
                <th>수량</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td><a href="item.html">1</a></td>
                <td><a href="item.html">테스트 상품1</a></td>
                <td>10000</td>
                <td>10</td>
            </tr>
            <tr>
                <td><a href="item.html">2</a></td>
                <td><a href="item.html">테스트 상품2</a></td>
                <td>20000</td>
                <td>20</td>
            </tr>
            </tbody>
        </table>
    </div>
</div> <!-- /container -->
</body>
</html>
  • /resources/static/html/item.html
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <style>
 .container {
 max-width: 560px;
 }
 </style>
</head>
<body>
<div class="container">
    <div class="py-5 text-center">
        <h2>상품 상세</h2>
    </div>
    <div>
        <label for="itemId">상품 ID</label>
        <input type="text" id="itemId" name="itemId" class="form-control"
               value="1" readonly>
    </div>
    <div>
        <label for="itemName">상품명</label>
        <input type="text" id="itemName" name="itemName" class="form-control"
               value="상품A" readonly>
    </div>
    <div>
        <label for="price">가격</label>
        <input type="text" id="price" name="price" class="form-control"
               value="10000" readonly>
    </div>
    <div>
        <label for="quantity">수량</label>
        <input type="text" id="quantity" name="quantity" class="form-control"
               value="10" readonly>
    </div>
    <hr class="my-4">
    <div class="row">
        <div class="col">
            <button class="w-100 btn btn-primary btn-lg"
                    onclick="location.href='editForm.html'" type="button">상품 수정</button>
        </div>
        <div class="col">
            <button class="w-100 btn btn-secondary btn-lg"
                    onclick="location.href='items.html'" type="button">목록으로</button>
        </div>
    </div>
</div> <!-- /container -->
</body>
</html>
  • /resources/static/html/addForm.html
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <style>
 .container {
 max-width: 560px;
 }
 </style>
</head>
<body>
<div class="container">
    <div class="py-5 text-center">
        <h2>상품 등록 폼</h2>
    </div>
    <h4 class="mb-3">상품 입력</h4>
    <form action="item.html" method="post">
        <div>
            <label for="itemName">상품명</label>
            <input type="text" id="itemName" name="itemName" class="formcontrol" placeholder="이름을 입력하세요">
        </div>
        <div>
            <label for="price">가격</label>
            <input type="text" id="price" name="price" class="form-control"
                   placeholder="가격을 입력하세요">
        </div>
        <div>
            <label for="quantity">수량</label>
            <input type="text" id="quantity" name="quantity" class="formcontrol" placeholder="수량을 입력하세요">
        </div>
        <hr class="my-4">
        <div class="row">
            <div class="col">
                <button class="w-100 btn btn-primary btn-lg" type="submit">상품
                    등록</button>
            </div>
            <div class="col">
                <button class="w-100 btn btn-secondary btn-lg"
                        onclick="location.href='items.html'" type="button">취소</button>
            </div>
        </div>
    </form>
</div> <!-- /container -->
</body>
</html>
  • /resources/static/html/editForm.html
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <style>
 .container {
 max-width: 560px;
 }
 </style>
</head>
<body>
<div class="container">
    <div class="py-5 text-center">
        <h2>상품 수정 폼</h2>
    </div>
    <form action="item.html" method="post">
        <div>
            <label for="id">상품 ID</label>
            <input type="text" id="id" name="id" class="form-control" value="1"
                   readonly>
        </div>
        <div>
            <label for="itemName">상품명</label>
            <input type="text" id="itemName" name="itemName" class="formcontrol" value="상품A">
        </div>
        <div>
            <label for="price">가격</label>
            <input type="text" id="price" name="price" class="form-control"
                   value="10000">
        </div>
        <div>
            <label for="quantity">수량</label>
            <input type="text" id="quantity" name="quantity" class="formcontrol" value="10">
        </div>
        <hr class="my-4">
        <div class="row">
            <div class="col">
                <button class="w-100 btn btn-primary btn-lg" type="submit">저장
                </button>
            </div>
            <div class="col">
                <button class="w-100 btn btn-secondary btn-lg"
                        onclick="location.href='item.html'" type="button">취소</button>
            </div>
        </div>
    </form>
</div> <!-- /container -->
</body>
</html>

## 상품목록_타임리프 사용

  • 컨트롤러와 뷰 템플릿 개발.

BasicItemController

package hello.itemservice.web.basic;

import hello.itemservice.domain.item.Item;
import hello.itemservice.domain.item.ItemRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import java.util.List;

@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
public class BasicItemController {

    private final ItemRepository itemRepository;

    @GetMapping
    public String items(Model model) {
        List<Item> items = itemRepository.findAll();
        model.addAttribute("items", items);
        return "basic/items";
    }

    /**
     * 테스트용 데이터 추가.
     * */
    @PostConstruct
    public void init() {
        itemRepository.save(new Item("itemA", 10000, 10));
        itemRepository.save(new Item("itemB", 20000, 20));
    }
}
  • @RequiredArgsConstructor : final 붙은 멤버변수만 사용, 생성자를 자동으로 만들어준다.

items.html

  • 아래 경로에 추가.
/resources/templates/basic/items.html
  • 속성 변경 : 기존 css href를 th:href로 변경.
<link th:href="@{/css/bootstrap.min.css}"
        href="../css/bootstrap.min.css" rel="stylesheet">
  • 속성변경 : 기존 상품 등록 폼 이동 onclick 변경
<button class="btn btn-primary float-end"
        onclick="location.href='addForm.html'"
        th:onclick="|location.href='@{/basic/items/add}'|"
        type="button">상품
    등록</button>
  •  반복 출력 : th:each 사용. 
<tr th:each="item : ${items}">
    <td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.id}">회원ID</a></td>
    <td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.itemName}">상품명</a></td>
    <td th:text="${item.price}">10000</td>
    <td th:text="${item.quantity}">10</td>
</tr>
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <link th:href="@{/css/bootstrap.min.css}"
            href="../css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="max-width: 600px">
    <div class="py-5 text-center">
        <h2>상품 목록</h2>
    </div>
    <div class="row">
        <div class="col">
            <button class="btn btn-primary float-end"
                    onclick="location.href='addForm.html'"
                    th:onclick="|location.href='@{/basic/items/add}'|"
                    type="button">상품
                등록</button>
        </div>
    </div>
    <hr class="my-4">
    <div>
        <table class="table">
            <thead>
            <tr>
                <th>ID</th>
                <th>상품명</th>
                <th>가격</th>
                <th>수량</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="item : ${items}">
                <td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.id}">회원ID</a></td>
                <td><a href="item.html" th:href="@{|/basic/items/${item.id}|}" th:text="${item.itemName}">상품명</a></td>
                <td th:text="${item.price}">10000</td>
                <td th:text="${item.quantity}">10</td>
            </tr>
            </tbody>
        </table>
    </div>
</div> <!-- /container -->
</body>
</html>

타임리프

  • 타임리프 사용 선언 : 타임리프 사용을 위해 아래와 같이 선언.
<html xmlns:th="http://www.thymeleaf.org">

속성 변경 : th:href

  • href="value1"을 th:href="value2"의 값으로 변경.
  • 타임리프 뷰 템플릿을 거치면서 원래 값을 th:xxx 로 변경한다. 만약 값이 없으면 새로 생성한다.
<link th:href="@{/css/bootstrap.min.css}"
        href="../css/bootstrap.min.css" rel="stylesheet">

속성 변경 : th:onclick

<button class="btn btn-primary float-end"
        onclick="location.href='addForm.html'"
        th:onclick="|location.href='@{/basic/items/add}'|"
        type="button">상품
    등록</button>

타임리프의 핵심

  • th:xxx가 붙은 부분은 서버사이드에서랜더링 되고, 기존 것을 대체한다. th:xxx가 없으면 기존 html의 xxx 속성이 그대로 사용된다.
  • HTML파일을 직접 열었을 때, th:xxx가 있어도 웹 브라우저는 th: 속성을 알지 못하므로 무시. (HTML 파일 보기를 유지하면서도 템플릿 기능도 할 수 있다.)

URL 링크 표현식 : @{ ... }

  • @{ } : 타임리프는 URL 링크를 사용하는 경우 @{ } 를 사용. (=URL 링크 표현식)
  • URL 링크 표현식을 사용하면 서블릿 컨텍스트를 자동으로 포함.
th:href="@{/css/bootstrap.min.css}"

URL 링크 표현식2 : @ { ... }

  • 상품 id 선택 시 링크.
<td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.id}">회원ID</a></td>
  • URL 경로 표현식을 이용하여 경로를 템플릿처럼 편리하게 사용.
  • 경로 변수 ( {item.id} ) 뿐만 아니라 쿼리 파라미터도 생성한다.
th:href="@{/basic/items/{itemId}(itemId=${item.id}, query='test')}" th:text="${item.id}"

=>
생성링크 : http://localhost:8080/basic/items/1?query=test

리터럴 대체 : | ... |

  • 타임리프에서 문자와 표현식 등은 분리되어 있기 때문에 더해서 사용해야 함.
<span th:text="'Welcome to our apllication, ' + ${user.name} + '!'">
  • 아래와 같이 리터럴 대체 문법 사용 시 더하기 없이 편리하게 사용 가능.
<span th:text="|Welcome to our apllication, ${user.name} !|">

반복 출력 : th:each

<tr th:each="item : ${items}">
  • 반복은 th:each 사용, 이렇게 하면 모델에 포함된 items 컬렉션 데이터가 item 변수에 하나씩 포함, 반복문 안에서 item 변수 사용 가능.
  • 컬렉션의 수 만큼 <tr> .. <tr>이 하위 태그를 포함해서 생성.
<tr th:each="item : ${items}">
    <td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.id}">회원ID</a></td>
    <td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.itemName}">상품명</a></td>
    <td th:text="${item.price}">10000</td>
    <td th:text="${item.quantity}">10</td>
</tr>

변수 표현식 : ${ ... }

<td th:text="${item.price}">10000</td>
  • 모델에 포함된 값이나, 타임리프 변수로 선언한 값을 조회.
  • 프로퍼티 접근법을 사용 ( item.getPrice() )

내용 변경 : th:text

<td th:text="${item.price}">10000</td>
  • 내용의 값을 th:text의 값으로 변경. 위 코드에서는 10000을 ${item.price} 값으로 변경.

##  상품 상세

BasicItemController : item 추가.

package hello.itemservice.web.basic;

import hello.itemservice.domain.item.Item;
import hello.itemservice.domain.item.ItemRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import java.util.List;

@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
public class BasicItemController {

    private final ItemRepository itemRepository;

    @GetMapping
    public String items(Model model) {
        List<Item> items = itemRepository.findAll();
        model.addAttribute("items", items);
        return "basic/items";
    }

    @GetMapping("/{itemId}")
    public String item(@PathVariable long itemId, Model model) {
        Item item = itemRepository.findById(itemId);
        model.addAttribute("item", item);
        return "basic/item";
    }

    /**
     * 테스트용 데이터 추가.
     * */
    @PostConstruct
    public void init() {
        itemRepository.save(new Item("itemA", 10000, 10));
        itemRepository.save(new Item("itemB", 20000, 20));
    }
}

item.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <link th:href="@{/css/bootstrap.min.css}"
          href="../css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            max-width: 560px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="py-5 text-center">
        <h2>상품 상세</h2>
    </div>
    <div>
        <label for="itemId">상품 ID</label>
        <input type="text" id="itemId" name="itemId" class="form-control" value="1" th:value="${item.id}" readonly>
    </div>
    <div>
        <label for="itemName">상품명</label>
        <input type="text" id="itemName" name="itemName" class="form-control" value="상품A" th:value="${item.itemName}" readonly>
    </div>
    <div>
        <label for="price">가격</label>
        <input type="text" id="price" name="price" class="form-control" value="10000" th:value="${item.price}" readonly>
    </div>
    <div>
        <label for="quantity">수량</label>
        <input type="text" id="quantity" name="quantity" class="form-control" value="10" th:value="${item.quantity}" readonly>
    </div>
    <hr class="my-4">
    <div class="row">
        <div class="col">
            <button class="w-100 btn btn-primary btn-lg"
                    onclick="location.href='editForm.html'"
                    th:onclick="|location.href='@{/basic/items/{itemId}/edit(itemId=${item.id})}'|"
                    type="button">상품 수정</button>
        </div>
        <div class="col">
            <button class="w-100 btn btn-secondary btn-lg"
                    onclick="location.href='items.html'"
                    th:onclick="|location.href='@{/basic/items}'|"
                    type="button">목록으로</button>
        </div>
    </div>
</div> <!-- /container -->
</body>
</html>

## 상품 등록 폼

BasicItemController : addForm 추가

package hello.itemservice.web.basic;

import hello.itemservice.domain.item.Item;
import hello.itemservice.domain.item.ItemRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import java.util.List;

@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
public class BasicItemController {

    private final ItemRepository itemRepository;

    @GetMapping
    public String items(Model model) {
        List<Item> items = itemRepository.findAll();
        model.addAttribute("items", items);
        return "basic/items";
    }

    @GetMapping("/{itemId}")
    public String item(@PathVariable long itemId, Model model) {
        Item item = itemRepository.findById(itemId);
        model.addAttribute("item", item);
        return "basic/item";
    }

    @GetMapping("/add")
    public String addForm() {
        return "basic/addForm";
    }

    /**
     * 테스트용 데이터 추가.
     * */
    @PostConstruct
    public void init() {
        itemRepository.save(new Item("itemA", 10000, 10));
        itemRepository.save(new Item("itemB", 20000, 20));
    }
}

addForm.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <link th:href="@{/css/bootstrap.min.css}"
          href="../css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            max-width: 560px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="py-5 text-center">
        <h2>상품 등록 폼</h2>
    </div>
    <h4 class="mb-3">상품 입력</h4>
    <form action="item.html" th:action method="post">
        <div>
            <label for="itemName">상품명</label>
            <input type="text" id="itemName" name="itemName" class="formcontrol" placeholder="이름을 입력하세요">
        </div>
        <div>
            <label for="price">가격</label>
            <input type="text" id="price" name="price" class="form-control"
                   placeholder="가격을 입력하세요">
        </div>
        <div>
            <label for="quantity">수량</label>
            <input type="text" id="quantity" name="quantity" class="formcontrol" placeholder="수량을 입력하세요">
        </div>
        <hr class="my-4">
        <div class="row">
            <div class="col">
                <button class="w-100 btn btn-primary btn-lg"
                        type="submit">상품등록</button>
            </div>
            <div class="col">
                <button class="w-100 btn btn-secondary btn-lg"
                        onclick="location.href='items.html'"
                        th:onclick="|location.href='@{/basic/items}'|"
                        type="button">취소</button>
            </div>
        </div>
    </form>
</div> <!-- /container -->
</body>
</html>

속성 변경 : th:action

  • HTML form에서 action 에 값이 없으면 현재 URL에 데이터를 전송한다.
  • 상품 등록 폼의 URL과 실제 상품 등록을 처리하는 URL을 동일하게 맞추고 HTTP 메서드로 두 기능을 구분.
상품 등록 폼 : GET /basic/items/add

상품 등록 처리 : POST /basic/items/add
  • 이렇게 하면 하나의 URL로 등록 폼과, 등록 처리를 깔끔하게 처리할 수 있다.

## 상품 등록 처리_@ModelAttribute

  • POST - HTML Form
content-type: application/x-www-form-urlencoded

메시지 바디에 쿼리 파리미터 형식으로 전달 itemName=itemA&price=10000&quantity=10

예) 회원 가입, 상품 주문, HTML Form 사용
  • 요청 파라미터 형식을 처리해야 하므로 @RequestParam 사용.

상품 등록 처리_@RequestParam

addItemV1 - BasicItemController에 추가

@PostMapping("/add")
public String addItemV1(@RequestParam String itemName,
                   @RequestParam int price,
                   @RequestParam Integer quantity,
                   Model model) {

    Item item = new Item();
    item.setItemName(itemName);
    item.setPrice(price);
    item.setQuantity(quantity);

    itemRepository.save(item);

    model.addAttribute("item", item);

    return "basic/item";
}

addItemV2 - BasicItemController에 추가

@PostMapping("/add")
    public String addItemV2(@ModelAttribute("item") Item item) {

        itemRepository.save(item);
//        model.addAttribute("item", item);     // 자동 추가, 생략 가능

        return "basic/item";
    }

@ModelAttribute 중요 기능

1. 요청 파라미터 처리

  • @ModelAttribute 는 Item 객체를 생성, 요청 파라미터의 값을 프로퍼티 접근법(setXxx)으로 입력해준다.

2. Model 추가

  • 모델(Model)에 @ModelAttribute 로 지정한 객체를 자동으로 넣어준다.
  • 위 코드에서 model.addAttribute("item", item) 가 주석처리 되어 있어도 잘 동작.
  • 모델에 데이터를 담을 때는 이름이 필요. 이름은 @ModelAttribute 에 지정한 name(value) 속성을 사용.
  • 만약 다음과 같이 @ModelAttribute 의 이름을 다르게 지정하면 다른 이름으로 모델에 포함된다.
  • @ModelAttribute("hello") Item item -> 이름을 hello 로 지정
  • model.addAttribute("hello", item); -> 모델에 hello 이름으로 저장

addItemV3 - BasicItemController에 추가

@PostMapping("/add")
    public String addItemV3(@ModelAttribute Item item) {
        // @ModelAttribute("item")에서 ("item") 생략 시 Item -> item이 modelAttribute 담기게 됨.
        itemRepository.save(item);
//        model.addAttribute("item", item);     // 자동 추가, 생략 가능

        return "basic/item";
    }
  • @ModelAttribute 의 이름을 생략할 수 있다. (@ModelAttribute 의 이름을 생략 시 모델에 저장될 때 클래스명을 사용. 이때 클래스의 첫글자만 소문자로 변경해서 등록한다.)
@ModelAttribute 클래스명 모델에 자동 추가되는 이름
Item -> item
HelloWorld -> helloWorld

addItemV4 - BasicItemController에 추가

@PostMapping("/add")
    public String addItemV4(Item item) {
        itemRepository.save(item);
//        model.addAttribute("item", item);     // 자동 추가, 생략 가능
        return "basic/item";
    }
  • @ModelAttribute 자체도 생략가능.
  • 대상 객체는 모델에 자동 등록.
  • 나머지 사항은 기존과 동일하다.

## 상품 수정.

BasicItemController : editForm 추가.

@GetMapping("/{itemId}/edit")
public String editForm(@PathVariable Long itemId, Model model) {
    Item item = itemRepository.findById(itemId);
    model.addAttribute("item", item);
    return "basic/editForm";
}

@PostMapping("/{itemId}/edit")
public String edit(@PathVariable Long itemId, @ModelAttribute Item item) {
    itemRepository.update(itemId, item);
    return "redirect:/basic/items/{itemId}";
}
  • 상품 수정은 상품 등록과 전체 프로세스가 유사.
GET /items/{itemId}/edit : 상품 수정 폼
POST /items/{itemId}/edit : 상품 수정 처리

리다이렉트

  • 상품 수정은 마지막에 뷰 템플릿을 호출하는 대신 상품 상세 화면으로 이동하도록 리다이렉트를 호출.
  • 스프링은 redirect:/... 으로 편리하게 리다이렉트를 지원.
redirect:/basic/items/{itemId}" 컨트롤러에 매핑된 @PathVariable 의 값은 redirect 에서도 사용 가능.

redirect:/basic/items/{itemId} {itemId} 는 @PathVariable Long itemId 의 값을 그대로 사용.

editForm.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <link th:href="@{/css/bootstrap.min.css}"
          href="../css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            max-width: 560px;
        }
     </style>
</head>
<body>
<div class="container">
    <div class="py-5 text-center">
        <h2>상품 수정 폼</h2>
    </div>
    <form action="item.html" th:action method="post">
        <div>
            <label for="id">상품 ID</label>
            <input type="text" id="id" name="id" class="form-control" value="1" th:value="${item.id}" readonly>
        </div>
        <div>
            <label for="itemName">상품명</label>
            <input type="text" id="itemName" name="itemName" class="formcontrol" value="상품A" th:value="${item.itemName}">
        </div>
        <div>
            <label for="price">가격</label>
            <input type="text" id="price" name="price" class="form-control" value="10000" th:value="${item.price}">
        </div>
        <div>
            <label for="quantity">수량</label>
            <input type="text" id="quantity" name="quantity" class="formcontrol" value="10" th:value="${item.quantity}">
        </div>
        <hr class="my-4">
        <div class="row">
            <div class="col">
                <button class="w-100 btn btn-primary btn-lg" type="submit">저장</button>
            </div>
            <div class="col">
                <button class="w-100 btn btn-secondary btn-lg"
                        onclick="location.href='item.html'"
                        th:onclick="|location.href='@{/basic/items/{itemId}(itemId=${item.id})}'|"
                        type="button">취소</button>
            </div>
        </div>
    </form>
</div> <!-- /container -->
</body>
</html>

## PRG : Post / Redirect / Get

  • 상품 등록 처리 컨트롤러는 심각한 문제 존재. (addItemV1 ~ addItemV4, 상품 등록을 완료하고 웹 브라우저의 새로고침 버튼을 클릭 시 상품이 계속해서 중복 등록.)
  • 웹 브라우저 새로고침 : 마지막에 서버에 전송한 데이터를 다시 전송 (마지막 행위를 다시 실행(데이터 까지 포함하여))
  • 새로고침 해결방법 : 리다이렉트

BasicItemController : addItemV5 추가.

    @PostMapping("/add")
    public String addItemV5(Item item) {
        itemRepository.save(item);
//        model.addAttribute("item", item);     // 자동 추가, 생략 가능
        return "redirect:/basic/items/" + item.getId();
    }

주의할점

  • "redirect:/basic/items/" + item.getId() redirect에서 +item.getId() 처럼 URL에 변수를 더해서 사용하는 것은 URL 인코딩이 안되기 때문에 위험. RedirectAttributes 를 사용.

## RedirectAttributes

  • 상품 저장이 잘 되었으면 상품 상세 화면에 "저장되었습니다" 라는 메시지를 보여달라는 요구사항.

BasicItemController : addItemV6 추가

@PostMapping("/add")
public String addItemV6(Item item, RedirectAttributes redirectAttributes) {
    Item saveItem = itemRepository.save(item);
    redirectAttributes.addAttribute("itemId", saveItem.getId());
    redirectAttributes.addAttribute("status", true);
    return "redirect:/basic/items/{itemId}";
}

item.html 수정

<!-- 추가 -->
<h2 th:if="${param.status}" th:text="'저장 완료'"></h2>
  • th:if : 해당 조건이 참이면 실행
  • ${param.status} : 타임리프에서 쿼리 파라미터를 편리하게 조회하는 기능, 원래는 컨트롤러에서 모델에 직접 담고 값을 꺼내야 하는데, 쿼리 파라미터는 자주 사용해서 타임리프에서 직접 지원.

## 정리

  1. 프로젝트 생성.
  2. 타임리프 사용.
  3. @ModelAttribute
  4. 리다이렉트.
  5. PRG Post/ Redirect / Get 패턴 : 등록 시 리다이렉트 이용하여 중복등록 방지.
  6. RedirectAttributes
반응형
반응형

# 스프링 MVC 기본 기능

## 응답 - 정적 리소스, 뷰 템플릿

  • 스프링(서버)에서 응답 데이터를 만드는 방법은 크게 3가지이다.

1. 정적 리소스

  • 예) 웹 브라우저에 정적인 HTML, css, js을 제공할 때, 정적 리소스 사용.

2. 뷰 템플릿 사용

  • 예) 웹 브라우저에 동적인 HTML을 제공할 때, 뷰 템플릿 사용.

3. HTTP 메시지 사용

  • HTTP API를 제공하는 경우, HTML이 아니라 데이터를 전달해야 하므로, HTTP 메시지 바디에 JSON 같은 형식으로 데이터를 실어 보낸다.

정적 리소스

  • 스프링 부트는 클래스패스의 다음 디렉토리에 있는 정적 리소스를 제공 : /static, /public, /resources, /META-INF/resources
  • 정적 리소스 : 해당 파일을 변경 없이 그대로 서비스하는 것.

뷰 템플릿

  • 뷰 템플릿을 거쳐 HTML이 생성되고, 뷰가 응답을 만들어서 전달.
  • 일반적으로 HTML을 동적으로 생성하는 용도로 사용 하지만, 다른 것들도 가능. (뷰 템플릿이 만들 수 있는 것이라면 뭐든지 가능.)
  • 뷰 템플릿 경로 
src/main/resources/templates
  • hello.html (뷰 템플릿)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${data}">empty</p>
</body>
</html>
  • ResponseViewController. (뷰 템플릿 사용을 위한 컨트롤러)
package hello.springmvc.basic.response;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ResponseViewController {

    @RequestMapping("/response-view-v1")
    public ModelAndView responseViewV1() {
        ModelAndView mav = new ModelAndView("response/hello")
                .addObject("data", "hello!");
        return mav;
    }
}
  • String을 반환하는 경우 - View or HTTP 메시지
@RequestMapping("/response-view-v2")
public String responseViewV2(Model model) {
    model.addAttribute("data", "hello!");
    return "response/hello";
}
  • @ResponseBody 가 없으면 response/hello 로 뷰 리졸버가 실행되어 뷰를 찾고, 렌더링.
  • @ResponseBody 가 있으면 뷰 리졸버를 실행하지 않고, HTTP 메시지 바디에 직접 response/hello 라는 문자 입력.
  • Void를 반환하는 경우 - 해당 방식은 명시성이 떨어지고 이렇게 딱 맞는 경우도 없어서, 권장하지 않는다.
@RequestMapping("/response/hello")
public void responseViewV3(Model model) {
    model.addAttribute("data", "hello!");
}

Thymeleaf 스프링 부트 설정

  • 다음 라이브러리를 추가 (build.gradle에 추가)
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
  • 스프링 부트가 자동으로 ThymeleafViewResolver 와 필요한 스프링 빈들을 등록. 그리고 아래 설정도 사용. (기본 값)
  • application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

## HTTP 응답 - HTTP API, 메시지 바디에 직접 입력

  • HTTP API를 제공하는 경우, HTML이 아닌 데이터를 전달해야 하므로, HTTP 메시지 바디에 JSON 같은 형식으로 데이터를 실어 보낸다.

ResponseBodyController.

package hello.springmvc.basic.response;

import hello.springmvc.basic.HelloData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
public class ResponseBodyController {

    @GetMapping("/response-body-string-v1")
    public void responseBodyV1(HttpServletResponse response) throws IOException {
        response.getWriter().write("OK");
    }

    @GetMapping("/response-body-string-v2")
    public ResponseEntity<String> responseBodyV2() {
        return new ResponseEntity<>("OK", HttpStatus.OK);
    }

    @ResponseBody
    @GetMapping("/response-body-string-v3")
    public String responseBodyV3() {
        return "OK";
    }

    @GetMapping("/response-body-json-v1")
    public ResponseEntity<HelloData> responseBodyJsonV1() {
        HelloData helloData = new HelloData();
        helloData.setUsername("userA");
        helloData.setAge(25);
        return new ResponseEntity<>(helloData, HttpStatus.OK);
    }

    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/response-body-json-v2")
    public HelloData responseBodyJsonV2() {
        HelloData helloData = new HelloData();
        helloData.setUsername("userA");
        helloData.setAge(25);
        return helloData;
    }
}

responseBodyJsonV1

  • ResponseEntity 를 반환. HTTP 메시지 컨버터를 통해 JSON 형식으로 변환되어서 반환.

responseBodyJsonV2

  • ResponseEntity 는 HTTP 응답 코드를 설정할 수 있는데, @ResponseBody 를 사용하면 설정하기 까다롭다.
  • @ResponseStatus(HttpStatus.OK) 애노테이션 : 응답 코드 설정할 수 있는 애노테이션. 물론 애노테이션이기 때문에 응답 코드를 동적으로 변경할 수는 없다. (프로그램 조건에 따라 동적으로 변경하려면 ResponseEntity 사용.)

@RestController (@Controller + @ResponseBody)

  • @Controller 대신 @RestController 애노테이션을 사용하면, 해당 컨트롤러에 모두 @ResponseBody 가 적용되는 효과.
  • 따라서 뷰 템플릿을 사용하는 것이 아닌, HTTP 메시지 바디에 직접 데이터를 입력한다.
  • 이름 그대로 Rest API(HTTP API)를 만들 때 사용하는 컨트롤러.
  • @ResponseBody 는 클래스 레벨에 두면 전체에 메서드에 적용, @RestController 에노테이션 안에 @ResponseBody 가 적용되어 있다.

## HTTP 메시지 컨버터

  • 뷰 템플릿으로 HTML을 생성해서 응답하는 것이 아닌, HTTP API처럼 JSON 데이터를 HTTP 메시지 바디에서 직접 읽거나 쓰는 경우 HTTP 메시지 컨버터를 사용하면 편리하다.

스프링 MVC는 다음의 경우 HTTP 메시지 컨버터를 적용.

  • HTTP 요청 : @RequestBody , HttpEntity(RequestEntity)
  • HTTP 응답 : @ResponseBody , HttpEntity(ResponseEntity)

HTTP 메시지 컨버터 인터페이스

org.springframework.http.converter.HttpMessageConverter
/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.http.converter;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;

/**
 * Strategy interface for converting from and to HTTP requests and responses.
 *
 * @author Arjen Poutsma
 * @author Juergen Hoeller
 * @author Rossen Stoyanchev
 * @since 3.0
 * @param <T> the converted object type
 */
public interface HttpMessageConverter<T> {

   /**
    * Indicates whether the given class can be read by this converter.
    * @param clazz the class to test for readability
    * @param mediaType the media type to read (can be {@code null} if not specified);
    * typically the value of a {@code Content-Type} header.
    * @return {@code true} if readable; {@code false} otherwise
    */
   boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

   /**
    * Indicates whether the given class can be written by this converter.
    * @param clazz the class to test for writability
    * @param mediaType the media type to write (can be {@code null} if not specified);
    * typically the value of an {@code Accept} header.
    * @return {@code true} if writable; {@code false} otherwise
    */
   boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

   /**
    * Return the list of media types supported by this converter. The list may
    * not apply to every possible target element type and calls to this method
    * should typically be guarded via {@link #canWrite(Class, MediaType)
    * canWrite(clazz, null}. The list may also exclude MIME types supported
    * only for a specific class. Alternatively, use
    * {@link #getSupportedMediaTypes(Class)} for a more precise list.
    * @return the list of supported media types
    */
   List<MediaType> getSupportedMediaTypes();

   /**
    * Return the list of media types supported by this converter for the given
    * class. The list may differ from {@link #getSupportedMediaTypes()} if the
    * converter does not support the given Class or if it supports it only for
    * a subset of media types.
    * @param clazz the type of class to check
    * @return the list of media types supported for the given class
    * @since 5.3.4
    */
   default List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
      return (canRead(clazz, null) || canWrite(clazz, null) ?
            getSupportedMediaTypes() : Collections.emptyList());
   }

   /**
    * Read an object of the given type from the given input message, and returns it.
    * @param clazz the type of object to return. This type must have previously been passed to the
    * {@link #canRead canRead} method of this interface, which must have returned {@code true}.
    * @param inputMessage the HTTP input message to read from
    * @return the converted object
    * @throws IOException in case of I/O errors
    * @throws HttpMessageNotReadableException in case of conversion errors
    */
   T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
         throws IOException, HttpMessageNotReadableException;

   /**
    * Write an given object to the given output message.
    * @param t the object to write to the output message. The type of this object must have previously been
    * passed to the {@link #canWrite canWrite} method of this interface, which must have returned {@code true}.
    * @param contentType the content type to use when writing. May be {@code null} to indicate that the
    * default content type of the converter must be used. If not {@code null}, this media type must have
    * previously been passed to the {@link #canWrite canWrite} method of this interface, which must have
    * returned {@code true}.
    * @param outputMessage the message to write to
    * @throws IOException in case of I/O errors
    * @throws HttpMessageNotWritableException in case of conversion errors
    */
   void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
         throws IOException, HttpMessageNotWritableException;

}
  • HTTP 메시지 컨버터는 HTTP 요청, HTTP 응답 둘 다 사용.
canRead() , canWrite() : 메시지 컨버터가 해당 클래스, 미디어타입을 지원하는지 체크.

read() , write() : 메시지 컨버터를 통해서 메시지를 읽고 쓰는 기능.

스프링 부트 기본 메시지 컨버터 (일부 생략)

0 = ByteArrayHttpMessageConverter

1 = StringHttpMessageConverter

2 = MappingJackson2HttpMessageConverter

주요한 메시지 컨버터

  • ByteArrayHttpMessageConverter : byte[] 데이터 처리.
클래스 타입: byte[] , 미디어타입: */*
요청 예) @RequestBody byte[] data
응답 예) @ResponseBody return byte[] 쓰기 미디어타입 application/octet-stream
  • StringHttpMessageConverter : String 문자로 데이터를 처리한다
클래스 타입: String , 미디어타입: */*
요청 예) @RequestBody String data
응답 예) @ResponseBody return "ok" 쓰기 미디어타입 text/plain
  • MappingJackson2HttpMessageConverter : application/json
클래스 타입: 객체 또는 HashMap , 미디어타입 application/json 관련
요청 예) @RequestBody HelloData data
응답 예) @ResponseBody return helloData 쓰기 미디어타입 application/json 관련

HTTP 요청 데이터 읽기

HTTP 요청이 오고, 컨트롤러에서 @RequestBody , HttpEntity 파라미터를 사용한다.

메시지 컨버터가 메시지를 읽을 수 있는지 확인하기 위해 canRead() 호출.

대상 클래스 타입을 지원하는가 : 예) @RequestBody 의 대상 클래스 ( byte[] , String , HelloData )

HTTP 요청의 Content-Type 미디어 타입을 지원하는가 : 예) text/plain , application/json , */*

canRead() 조건을 만족하면 read() 를 호출해서 객체 생성하고, 반환.

HTTP 응답 데이터 생성

컨트롤러에서 @ResponseBody , HttpEntity 로 값 반환.

메시지 컨버터가 메시지를 쓸 수 있는지 확인하기 위해 canWrite() 를 호출.

대상 클래스 타입을 지원하는가 : 예) return의 대상 클래스 ( byte[] , String , HelloData )

HTTP 요청의 Accept 미디어 타입을 지원하는가(정확히는 @RequestMapping 의 produces) : 예) text/plain , application/json , */*

canWrite() 조건을 만족하면 write() 를 호출해서 HTTP 응답 메시지 바디에 데이터를 생성.

## 요청 매핑 헨들러 어뎁터 구조 (RequestMappingHandlerAdapter)

  • @RequestMapping 을 처리하는 핸들러 어댑터인 RequestMappingHandlerAdapter (요청 매핑 헨들러 어뎁터)

ArgumentResolver (파라미터 처리!)

  • 애노테이션 기반의 컨트롤러는 매우 다양한 파라미터를 사용. HttpServletRequest , Model 은 물론이고, @RequestParam , @ModelAttribute 같은 애노테이션 그리고 @RequestBody , HttpEntity 같은 HTTP 메시지를 처리하는 부분까지 큰 유연함을 보여주었다.
  • 이렇게 파라미터를 유연하게 처리할 수 있는 이유가 바로 ArgumentResolver 덕분.
  • 애노테이션 기반 컨트롤러를 처리하는 RequestMappingHandlerAdaptor 는 바로 이 ArgumentResolver 를 호출해 컨트롤러(핸들러)가 필요로 하는 다양한 파라미터의 값(객체)을 생성. 그리고 파리미터의 값이 모두 준비되면 컨트롤러를 호출하면서 값을 넘겨준다.
  • 스프링은 30개가 넘는 ArgumentResolver 를 기본으로 제공. (HandlerMethodArgumentResolver 인데 줄여서 ArgumentResolver 라고 부른다)
/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.method.support;

import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * Strategy interface for resolving method parameters into argument values in
 * the context of a given request.
 *
 * @author Arjen Poutsma
 * @since 3.1
 * @see HandlerMethodReturnValueHandler
 */
public interface HandlerMethodArgumentResolver {

   /**
    * Whether the given {@linkplain MethodParameter method parameter} is
    * supported by this resolver.
    * @param parameter the method parameter to check
    * @return {@code true} if this resolver supports the supplied parameter;
    * {@code false} otherwise
    */
   boolean supportsParameter(MethodParameter parameter);

   /**
    * Resolves a method parameter into an argument value from a given request.
    * A {@link ModelAndViewContainer} provides access to the model for the
    * request. A {@link WebDataBinderFactory} provides a way to create
    * a {@link WebDataBinder} instance when needed for data binding and
    * type conversion purposes.
    * @param parameter the method parameter to resolve. This parameter must
    * have previously been passed to {@link #supportsParameter} which must
    * have returned {@code true}.
    * @param mavContainer the ModelAndViewContainer for the current request
    * @param webRequest the current request
    * @param binderFactory a factory for creating {@link WebDataBinder} instances
    * @return the resolved argument value, or {@code null} if not resolvable
    * @throws Exception in case of errors with the preparation of argument values
    */
   @Nullable
   Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
         NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception;

}

 

  • 동작방식 : ArgumentResolver 의 supportsParameter() 를 호출 해당 파라미터를 지원하는지 체크, 지원하면 resolveArgument() 를 호출해서 실제 객체를 생성. 그리고 이렇게 생성된 객체가 컨트롤러 호출 시 넘어간다.

ReturnValueHandler

  • HandlerMethodReturnValueHandler 를 줄여 ReturnValueHandle 라고 부른다.
  • ArgumentResolver 와 비슷한데, 이것은 응답 값을 변환하고 처리.
  • 컨트롤러에서 String으로 뷰 이름을 반환해도, 동작하는 이유가 바로 ReturnValueHandler 덕분이다.
  • 스프링은 10여개가 넘는 ReturnValueHandler 를 지원. (ModelAndView , @ResponseBody , HttpEntity , String 등)

HTTP 메시지 컨버터

  • HTTP 메시지 컨버터를 사용하는 @RequestBody 도 컨트롤러가 필요로 하는 파라미터의 값에 사용.
  • @ResponseBody 도 컨트롤러의 반환 값을 이용.
  • ArgumentResolver은 HTTP 메서지 컨버터 사용. 

요청

  • @RequestBody 를 처리하는 ArgumentResolver, HttpEntity 를 처리하는 ArgumentResolver 가 존재.
  • 이 ArgumentResolver 들이 HTTP 메시지 컨버터를 사용해서 필요한 객체를 생성하는 것.

응답

  • @ResponseBody 와 HttpEntity 를 처리하는 ReturnValueHandler 가 존재. 그리고 여기에서 HTTP 메시지 컨버터를 호출해서 응답 결과를 만든다.
  • 스프링 MVC는 @RequestBody @ResponseBody 가 있으면 RequestResponseBodyMethodProcessor (ArgumentResolver), HttpEntity 가 있으면 HttpEntityMethodProcessor (ArgumentResolver)를 사용.

확장

  • 스프링은 다음을 모두 인터페이스로 제공. (필요하면 언제든 기능 확장가능.)
  • HandlerMethodArgumentResolver
  • HandlerMethodReturnValueHandler
  • HttpMessageConverter
  • 기능 확장 : WebMvcConfigurer 를 상속 받아 스프링 빈으로 등록하면 된다.
반응형
반응형

# 스프링 MVC 기본 기능

## HTTP 요청 - 기본, 헤더 조회

  • 애노테이션 기반의 스프링 컨트롤러는 다양한 파라미터를 지원.
  • RequestHeaderController.
package hello.springmvc.basic.request;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Slf4j
@RestController
public class RequestHeaderController {

    @RequestMapping("/headers")
    public String headers(HttpServletRequest request
            , HttpServletResponse response
            , HttpMethod httpMethod
            , Locale locale
            , @RequestHeader MultiValueMap<String, String> headerMap
            , @RequestHeader("host") String host
            , @CookieValue(value = "myCookie", required = false) String cookie) {

        log.info("request={}", request);
        log.info("response={}", response);
        log.info("httpMethod={}", httpMethod);
        log.info("locale={}", locale);
        log.info("headerMap={}", headerMap);
        log.info("header host={}", host);
        log.info("myCookie={}", cookie);

        return "OK";
    }
}
  • HttpServletRequest
  • HttpServletResponse
  • HttpMethod : HTTP 메서드를 조회한다. org.springframework.http.HttpMethod
  • Locale : Locale 정보를 조회한다.
  • @RequestHeader MultiValueMap headerMap, 모든 HTTP 헤더를 MultiValueMap 형식으로 조회.
  • @RequestHeader("host") String host : 특정 HTTP 헤더를 조회.
속성
필수 값 여부 : required
기본 값 속성 : defaultValue
  • @CookieValue(value = "myCookie", required = false) String cookie : 특정 쿠키를 조회.
속성
필수 값 여부 : required
기본 값 : defaultValue
  • MultiValueMap  : MAP과 유사, 하나의 키에 여러 값을 받을 수 있다, HTTP header, HTTP 쿼리 파라미터와 같이 하나의 키에 여러 값을 받을 때 사용.
keyA=value1&keyA=value2
 

Web on Servlet Stack

Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, “Spring Web MVC,” comes from the name of its source module (spring-webmvc), but it is more com

docs.spring.io

 

Web on Servlet Stack

Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, “Spring Web MVC,” comes from the name of its source module (spring-webmvc), but it is more com

docs.spring.io

## HTTP 요청 파라미터 - 쿼리 파라미터, HTML Form

  • 클라이언트에서 서버로 요청 데이터 전달 시 다음 3가지 방법을 사용.

1. GET - 쿼리 파라미터

/url?username=hello&age=20

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

예) 검색, 필터, 페이징등에서 많이 사용.

2. POST - HTML Form

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

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

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

3. HTTP message body

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

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

데이터 형식은 주로 JSON 사용

POST, PUT, PATCH

요청 파라미터 - 쿼리 파라미터, HTML Form

  • HttpServletRequest 의 request.getParameter() 사용 시 다음 두가지 요청 파라미터 조회.
  • GET 쿼리 파리미터 전송 방식, POST HTML Form 전송 방식 둘다 형식이 같으므로 구분없이 조회할 수 있다. (요청 파라미터(request parameter) 조회)

RequestParamController

package hello.springmvc.basic.request;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
public class RequestParamController {

    @RequestMapping("/request-param-v1")
    public void requestParamV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        log.info("username={}, age={}", username, age);

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

hello-form.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/request-param-v1" method="post">
    username: <input type="text" name="username" />
    age: <input type="text" name="age" />
    <button type="submit">전송</button>
</form>
</body>
</html>
  • 리소스는 /resources/static 아래에 두면 스프링 부트가 자동으로 인식.

## HTTP 요청 파라미터 - @RequestParam

  • 스프링이 제공하는 @RequestParam 을 사용하면 요청 파라미터를 편리하게 사용할 수 있다.

requestParamV2.

@ResponseBody   // @RestController 동일한 역할.
@RequestMapping("/request-param-v2")
public String requestParamV2(
        @RequestParam("username") String memberName,
        @RequestParam("age") int memberAge) {
    log.info("username={}, age={}", memberName, memberAge);

    return "OK";
}
  • @RequestParam : 파라미터 이름으로 바인딩
  • @ResponseBody : View 조회를 무시하고, HTTP message body에 직접 해당 내용 입력.

requestParamV3.

  • HTTP 파라미터 이름이 변수 이름과 같으면 @RequestParam(name="xx") 생략 가능
@ResponseBody
@RequestMapping("/request-param-v3")
public String requestParamV3(
        @RequestParam String username,
        @RequestParam int age) {
    log.info("username={}, age={}", username, age);

    return "OK";
}

requestParamV4.

  • String , int , Integer 등 단순 타입이면 @RequestParam 생략 가능.
@ResponseBody
@RequestMapping("/request-param-v4")
public String requestParamV4(String username, int age) {
    log.info("username={}, age={}", username, age);

    return "OK";
}

파라미터 필수 여부 - requestParamRequired

  • @RequestParam.required : 파라미터 필수 여부 (기본값 : 파라미터 필수(true))
  • true인 값이 없으면 400 예외 발생.
@ResponseBody
@RequestMapping("/request-param-required")
public String requestParamRequired(
        @RequestParam(required = true) String username,
        @RequestParam(required = false) int age) {
    log.info("username={}, age={}", username, age);

    return "OK";
}
  • 기본형(primitive)에 null 입력 시 (@RequestParam(required = false) int age 인 경우 null 입력 시.) null 을 int 에 입력하는 것은 불가능(500 예외 발생)
  • 따라서 null 을 받을 수 있는 Integer 로 변경하거나, defaultValue 사용.

기본 값 적용 - requestParamDefault

@ResponseBody
@RequestMapping("/request-param-default")
public String requestParamDefault(
        @RequestParam(required = true, defaultValue = "guest") String username,
        @RequestParam(required = false, defaultValue = "-1") int age) {
    log.info("username={}, age={}", username, age);

    return "OK";
}
  • 파라미터에 값이 없는 경우 defaultValue 를 사용 시 기본 값을 적용할 수 있다.
  • 이미 기본 값이 있기 때문에 required 는 의미없다.
  • defaultValue 는 빈 문자의 경우에도 설정한 기본 값이 적용된다.
/request-param?username=

파라미터를 Map으로 조회하기 - requestParamMap

@ResponseBody
@RequestMapping("/request-param-map")
public String requestParamMap(@RequestParam Map<String, Object> paramMap) {
    log.info("username={}, age={}", paramMap.get("username"), paramMap.get("age"));

    return "OK";
}
  • 파라미터를 Map, MultiValueMap으로 조회할 수 있다.
@RequestParam Map
	- Map(key=value)

@RequestParam MultiValueMap
	- MultiValueMap(key=[value1, value2, ...] ex) (key=userIds, value=[id1, id2])
  • 파라미터 값이 1개가 확실하면 Map 사용, 그렇지 않다면 MultiValueMap 사용.

## HTTP 요청 파라미터 - @ModelAttribute

HelloData.

package hello.springmvc.basic;

import lombok.Data;

@Data
public class HelloData {
    private String username;
    private int age;
}

modelAttributeV1

@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {
    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

    return "OK";
}
  • 스프링MVC는 @ModelAttribute 가 있으면 다음을 실행.
HelloData 객체 생성.

요청 파라미터의 이름으로 HelloData 객체의 프로퍼티를 찾고 
해당 프로퍼티의 setter를 호출해서 파라미터의 값을 입력(바인딩) 한다.

예) 파라미터 이름이 username 이면 setUsername() 메서드를 찾아서 호출하면서 값을 입력한다.
  • 프로퍼티
객체에 getUsername() , setUsername() 메서드가 있으면, 
이 객체는 username 이라는 프로퍼티를 가지고 있다.

username 프로퍼티의 값을 변경하면 setUsername() 호출, 조회하면 getUsername() 호출.
  • 바인딩 오류 (BindException)
age=abc 처럼 숫자가 들어가야 할 곳에 문자를 넣으면 BindException 발생.

@ModelAttribute 생략 - modelAttributeV2

@ResponseBody
@RequestMapping("/model-attribute-v2")
public String modelAttributeV2(HelloData helloData) {
    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

    return "OK";
}
  • @ModelAttribute 생략 가능, 그런데 @RequestParam 도 생략 가능하여 혼란이 발생할 수 있다.
  • 스프링은 해당 생략 시 다음의 규칙을 적용.
String , int , Integer 같은 단순 타입 = @RequestParam 

나머지 = @ModelAttribute (argument resolver 로 지정해둔 타입 외)

## HTTP 요청 메시지 - 단순 텍스트

  • HTTP message body에 데이터를 직접 담아서 요청 : HTTP API에서 주로 사용, JSON, XML, TEXT, 데이터 형식은 주로 JSON 사용, POST, PUT, PATCH
  • 요청 파라미터와 다르게, HTTP 메시지 바디를 통해 데이터가 직접 넘어오는 경우 @RequestParam , @ModelAttribute 를 사용할 수 없다.
  • HTTP 메시지 바디의 데이터를 InputStream 을 사용해서 직접 읽을 수 있다.

 RequestBodyStringController.

package hello.springmvc.basic.request;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Controller
public class RequestBodyStringController {

    @PostMapping("/request-body-string-v1")
    public void requestBodyString(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        log.info("messageBody={}", messageBody);

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

requestBodyStringV2. - Input, Output 스트림, Reader

@PostMapping("/request-body-string-v2")
public void requestBodyStringV2(InputStream inputStream, Writer responseWriter) throws IOException {
    String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

    log.info("messageBody={}", messageBody);

    responseWriter.write("OK");
}

스프링 MVC는 다음 파라미터를 지원.

InputStream(Reader) : HTTP 요청 메시지 바디의 내용을 직접 조회

OutputStream(Writer) : HTTP 응답 메시지의 바디에 직접 결과 출력

requestBodyStringV3. - HttpEntity 

@PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) throws IOException {
    String body = httpEntity.getBody();

    log.info("messageBody={}", body);

    return new HttpEntity<>("OK");
}

스프링 MVC는 다음 파라미터를 지원.

  • HttpEntity : HTTP header, body 정보를 편리하게 조회 메시지 바디 정보를 직접 조회 (요청 파라미터를 조회하는 기능과 관계 없음 @RequestParam X, @ModelAttribute X)
  • HttpEntity는 응답에도 사용 가능, 메시지 바디 정보 직접 반환, 헤더 정보 포함 가능 (view 조회X)

HttpEntity 를 상속받은 다음 객체들도 같은 기능 제공.

  • RequestEntity : HttpMethod, url 정보가 추가, 요청에서 사용.
  • ResponseEntity : HTTP 상태 코드 설정 가능, 응답에서 사용
return new ResponseEntity("Hello World", responseHeaders, HttpStatus.CREATED)

requestBodyStringV4 - @RequestBody (가장 자주 사용!!!)

@PostMapping("/request-body-string-v4")
public HttpEntity<String> requestBodyStringV4(@RequestBody String messageBody) throws IOException {
    log.info("messageBody={}", messageBody);

    return new HttpEntity<>("OK");
}
  • @RequestBody 를 사용하면 HTTP 메시지 바디 정보를 편리하게 조회할 수 있다.
  • 헤더 정보가 필요하면 HttpEntity 또는 @RequestHeader 를 사용.
  • 이렇게 메시지 바디를 직접 조회하는 기능은 요청 파라미터를 조회하는 @RequestParam , @ModelAttribute 와 전혀 관계가 없다.

정리.

  • 요청 파라미터를 조회하는 기능 : @RequestParam , @ModelAttribute
  • HTTP 메시지 바디를 직접 조회하는 기능 : @RequestBody

## HTTP 요청 메시지 - JSON

RequestBodyJsonController.

package hello.springmvc.basic.request;

import com.fasterxml.jackson.databind.ObjectMapper;
import hello.springmvc.basic.HelloData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Controller
public class RequestBodyJsonController {

    private ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/request-body-json-v1")
    public void requestBodyJson(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        log.info("messageBody={}", messageBody);
        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
        log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

        response.getWriter().write("OK");
    }
}
  • HttpServletRequest를 사용해 직접 HTTP 메시지 바디에서 데이터를 읽어와서, 문자로 변환.
  • 문자로 된 JSON 데이터를 Jackson 라이브러리인 objectMapper 를 사용해 자바 객체로 변환.

requestBodyJsonV2 - @RequestBody 문자 변환

@ResponseBody
@PostMapping("/request-body-json-v2")
public String requestBodyJsonV2(@RequestBody String messageBody) throws IOException {
    log.info("messageBody={}", messageBody);
    HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

    return "OK";
}

requestBodyJsonV3 - @RequestBody 객체 변환

@ResponseBody
@PostMapping("/request-body-json-v3")
public String requestBodyJsonV3(@RequestBody HelloData helloData) throws IOException {
    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

    return "OK";
}

@RequestBody 객체 파라미터

  • @RequestBody HelloData data @RequestBody 에 직접 만든 객체를 지정할 수 있다.
  • HttpEntity , @RequestBody 를 사용하면 HTTP 메시지 컨버터가 HTTP 메시지 바디의 내용을 원하는 문자나 객체 등 으로 변환.
  • HTTP 메시지 컨버터는 문자 뿐만 아니라 JSON도 객체로 변환.

@RequestBody 생략 불가능.

  • 스프링은 @ModelAttribute , @RequestParam 생략시 다음과 같은 규칙을 적용.
String , int , Integer 등 단순 타입 = @RequestParam 적용

나머지 = @ModelAttribute 적용(argument resolver 로 지정해둔 타입 외)

requestBodyJsonV4 - HttpEntity

@ResponseBody
@PostMapping("/request-body-json-v4")
public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) throws IOException {
    HelloData helloData = httpEntity.getBody();
    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());

    return "OK";
}

requestBodyJsonV5

@ResponseBody
@PostMapping("/request-body-json-v5")
public HelloData requestBodyJsonV5(@RequestBody HelloData data) throws IOException {
    log.info("username={}, age={}", data.getUsername(), data.getAge());

    return data;
}
  • @ResponseBody 응답의 경우에도 @ResponseBody 를 사용하면 해당 객체를 HTTP 메시지 바디에 직접 넣어줄 수 있다. 이 경우에도 HttpEntity 를 사용해도 된다.
  • @RequestBody 요청 : JSON 요청 > HTTP 메시지 컨버터 > 객체
  • @ResponseBody 응답 : 객체 > HTTP 메시지 컨버터 > JSON 응답
반응형
반응형

# 스프링 MVC 기본 기능

## 프로젝트 생성.

  • 아래와 같이 설정 후 GENERATE 진행.

Packaging : War가 아닌 Jar 선택 이유.

  • JSP를 사용하지 않기 때문에 Jar를 사용하는 것이 좋음.
  • 스프링 부트를 사용하면 이 방식을 주로 사용.
  • Jar를 사용하면 항상 내장 서버(톰캣등)을 사용, webapp 경로도 사용하지 않는니다. 내장 서버 사용에 최적화 되어 있는 기능으로 최근에는 주로 이 방식을 사용.
  • War를 사용하면 내장 서버도 사용가능 하지만, 주로 외부 서버에 배포하는 목적으로 사용.

build.gradle

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

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

configurations {
   compileOnly {
      extendsFrom annotationProcessor
   }
}

repositories {
   mavenCentral()
}

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

tasks.named('test') {
   useJUnitPlatform()
}

lombok 세팅

  • File > Settings 에서 annotation processors 검색 후 Enable annotation processing 체크.

Port 변경.

  • 8080 사용 중일 경우, run > edit configurations > Environment variable 에 아래와 같이 입력하여 port 변경.
server.port=8082

작동확인

설정 후 아래 클래스 진입하여 실행. (http://localhost:8080)

SpringmvcApplication

Welcome 페이지 생성.

  • 스프링 부트에 Jar 사용 시 /resources/static/index.hml 위치에 index.html 파일을 두게되면 Welcome 페이지로 처리. (스프링 부트가 지원하는 정적 컨텐츠 위치에 /index.html 이 있으면 된다.)

## 로깅 간단히 알아보기 (최소한의 기능)

  • 운영 시스템에서는 System.out.println() 같은 시스템 콘솔을 사용해서 필요한 정보를 출력하지 않고, 별도의 로깅 라이브러리를 사용해 로그를 출력.
  • 로그 관련 라이브러리도 많고, 깊게 들어가면 끝이 없음. (Logback, Log4J, Log4J2 등 수 많은 라이브러리 존재)

로깅 라이브러리

  • 스프링 부트 라이브러리를 사용하면 스프링 부트 로깅 라이브러리( spring-boot-starter-logging )가 함께 포함.
  • 스프링 부트 로깅 라이브러리는 기본으로 아래의 로깅 라이브러리 사용.
  • SLF4J (인터페이스) - http://www.slf4j.org
 

SLF4J

Simple Logging Facade for Java (SLF4J) The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framewor

www.slf4j.org

 

Logback Home

Logback Project Logback is intended as a successor to the popular log4j project, picking up where log4j 1.x leaves off. Logback's architecture is quite generic so as to apply under different circumstances. At present time, logback is divided into three mod

logback.qos.ch

  • 로그 라이브러리는 Logback, Log4J, Log4J2 등 많은 라이브러리가 있는데, 그것을 통합해서 인터페이스로 제공하는 것이 바로 SLF4J 라이브러리.
  • SLF4J는 인터페이스이고, 그 구현체로 Logback 같은 로그 라이브러리를 선택.
  • 실무에서는 스프링 부트가 기본 제공하는 Logback을 대부분 사용. (성능, 기능 괜찮음)

로그 선언

  • private Logger log = LoggerFactory.getLogger(getClass());
  • private static final Logger log = LoggerFactory.getLogger(Xxx.class)
  • @Slf4j : 롬복 사용 가능

로그 호출

  • log.info("hello")
  • System.out.println("hello") 시스템 콘솔로 직접 출력하는 것 보다 로그를 사용하면 다음과 같은 장점이 있다.
  • 실무에서는 항상 로그를 사용해야 한다.

LogTestController.

package hello.springmvc.basic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LogTestController {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @RequestMapping("/log-test")
    public String logTest() {
        String name = "Spring";

        log.trace("trace log = {} ", name);
        log.debug("debug log = {} ", name);
        log.info("info log = {} ", name);
        log.warn("warn log = {} ", name);
        log.error("error log = {} ", name)

        return "OK";
    }
}
  • System.out.println("hello") 의 경우 운영/개발 할것없이 항상 출력되므로 사용 하지 않는다. (로그 레벨 설정하여 로그 사용!!!!)

매핑 정보

  • @RestController @Controller 는 반환 값이 String 이면 뷰 이름으로 인식. 그래서 뷰를 찾고 뷰가 랜더링 된다.
  • @RestController 는 반환 값으로 뷰를 찾는 것이 아닌, HTTP 메시지 바디에 바로 입력. 따라서 실행 결과로 ok 메세지를 받을 수 있다.

로그 레벨 설정 (application.properties 에 입력) -> 기본 : info

  • 모든 로그를 출력 할 경우 trace
# hello.springmvc 패키지와 그 하위 로그 레벨 설정
logging.level.hello.springmvc=trace
  • trace 제외 debug 하위 레벨 출력 할 경우 debug
# hello.springmvc 패키지와 그 하위 로그 레벨 설정
logging.level.hello.springmvc=debug
  • info 하위 레벨 출력 할 경우 info (기본)
# hello.springmvc 패키지와 그 하위 로그 레벨 설정
logging.level.hello.springmvc=info

 

올바른 로그 사용법

  • log.debug("data="+data) 로그 출력 레벨을 info로 설정해도 해당 코드에 있는 "data="+data가 실제 실행이 되어 버린다. 결과적으로 문자 더하기 연산이 발생.
  • log.debug("data={}", data) 로그 출력 레벨을 info로 설정하면 아무일도 발생하지 않는다. 따라서 앞과 같은 의미없는 연산이 발생하지 않는다.
// 자바언어는 아래의 경우 "trace my log = " + "Spring"로 치환 후 더함(연산 발생)
// 로그 레벨을 debug로 할 경우 trace 사용하지 않아도 연산 일어남으로써 
// -> 메모리, cpu 사용. (쓸모없는 리소스 사용 / 의미없는 연산 발생.)
log.trace("trace my log = " + name);

로그가 출력되는 포멧 확인

  • 시간, 로그 레벨, 프로세스 ID, 쓰레드 명, 클래스명, 로그 메시지

로그 레벨 설정을 변경에 따른 출력 결과

  • LEVEL : TRACE > DEBUG > INFO > WARN > ERROR
  • 개발 서버 : debug 출력
  • 운영 서버 : info 출력

@Slf4j

  • lombok이 제공하는 것.
  • @Slf4j를 넣을 경우 아래 코드를 자동으로 해줌.
private final Logger log = LoggerFactory.getLogger(getClass());

로그 사용 장점

  • 시스템 아웃 콘솔에만 출력하는 것이 아니라, 파일이나 네트워크 등, 로그를 별도의 위치에 남길 수 있다.
  • 특히 파일로 남길 때는 일별, 특정 용량에 따라 로그를 분할하는 것도 가능하다.
  • 성능도 System.out보다 좋음. (내부 버퍼링, 멀티 쓰레드 등)
  • 실무에서는 꼭 로그 사용.

로그 추가 학습 시 참고.

로그에 대해서 더 자세한 내용은

스프링 부트가 제공하는 로그 기능

## 요청 매핑

MappingController.

package hello.springmvc.basic.requestmapping;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MappingController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @RequestMapping("/hello-basic")
    public String helloBasic() {
        log.info("basic");

        return "OK";
    }
}

@RestController

  • @Controller 는 반환 값이 String 이면 뷰 이름으로 인식. 그래서 뷰를 찾고 뷰가 랜더링 된다.
  • @RestController 는 반환 값으로 뷰를 찾는 것이 아난, HTTP 메시지 바디에 바로 입력. 따라서 실행 결과로 ok 메세지를 받을 수 있다.

@RequestMapping("/hello-basic")

  • /hello-basic URL 호출이 오면 이 메서드가 실행되도록 매핑.
  • 대부분의 속성을 배열[] 로 제공하므로 다중 설정이 가능하다. 
@RequestMapping({"/hello-basic", "/hello-go"})

두가지 모두 허용.

  • 다음 두가지 요청은 다른 URL이지만, 스프링은 다음 URL 요청들을 같은 요청으로 매핑.
  • 매핑 : /hello-basic
  • URL 요청 : /hello-basic , /hello-basic/

HTTP 메서드

  • @RequestMapping 에 method 속성으로 HTTP 메서드를 지정하지 않으면, HTTP 메서드와 무관하게 호출.
  • 모두 허용 GET, HEAD, POST, PUT, PATCH, DELETE
  • 아래와 같이 설정해줘야 함.
@RequestMapping(value = "/hello-basic", method = RequestMethod.GET)
  • 아래와 같이 축약 가능.
@GetMapping("/hello-basic")
package hello.springmvc.basic.requestmapping;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MappingController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/hello-basic")
    public String helloBasic() {
        log.info("basic");

        return "OK";
    }

    @RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
    public String mappingGetV1() {
        log.info("mappingGetV1");

        return "OK";
    }

    /**
     * 편리한 축약 애노테이션
     * @GetMapping
     * @PostMapping
     * @PutMapping
     * @DeleteMapping
     * @PatchMapping
     * */
    @GetMapping(value = "/mapping-get-v2")
    public String mappingGetV2() {
        log.info("mappingGetV2");

        return "OK";
    }
}

PathVariable(경로 변수) 사용 (자주 사용!!!!!)

/**
 * PathVariable 사용
 * 변수명이 같으면 생략 가능.
 * @PathVariable("userId") String userId -> @PathVariable userId
 * url 자체에 /mapping/userA 이런식으로 값이 들어감.
 */
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
    log.info("mappingPath userId = {} ", data);

    return "OK";
}
  • 최근 HTTP API는 아래와 같이 리소스 경로에 식별자를 넣는 스타일을 선호.
/mapping/userA

/users/1
  • @RequestMapping 은 URL 경로를 템플릿화 할 수 있는데, @PathVariable 을 사용하면 매칭 되는 부분을 편리하게 조회할 수 있다.
  • @PathVariable 의 이름과 파라미터 이름이 같으면 생략 가능 (아래 코드 참고) (단, @PathVariable 자체를 생략하는건 안됨.)

 

@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable String userId) {
    log.info("mappingPath userId = {} ", userId);

    return "OK";
}

PathVariable 사용 - 다중

/**
 * PathVariable 사용 - 다중
 */
@GetMapping("/mapping/users/{userId}/orders/{orderId}")
public String mappingPath(@PathVariable String userId, @PathVariable Long orderId) {
    log.info("mappingPath userId={}, orderId={}", userId, orderId);

    return "ok";
}

특정 파라미터 조건 매핑 (자주 사용하진 않음)

  • 특정 파라미터가 있거나 없는 조건을 추가할 수 있다.
/**
 * 파라미터로 추가 매핑
 * params="mode",
 * params="!mode"
 * params="mode=debug"
 * params="mode!=debug" (! = )
 * params = {"mode=debug","data=good"}
 */
@GetMapping(value = "/mapping-param", params = "mode=debug")
public String mappingParam() {
    log.info("mappingParam");
    
    return "ok";
}

특정 헤더 조건 매핑

/**
 * 특정 헤더로 추가 매핑
 * headers="mode",
 * headers="!mode"
 * headers="mode=debug"
 * headers="mode!=debug" (! = )
 */
@GetMapping(value = "/mapping-header", headers = "mode=debug")
public String mappingHeader() {
    log.info("mappingHeader");

    return "ok";
}

미디어 타입 조건 매핑 - HTTP 요청 Content-Type, consume

/**
 * Content-Type 헤더 기반 추가 매핑 Media Type
 * consumes="application/json"
 * consumes="!application/json"
 * consumes="application/*"
 * consumes="*\/*"
 * MediaType.APPLICATION_JSON_VALUE
 */
@PostMapping(value = "/mapping-consume", consumes = "application/json")
public String mappingConsumes() {
    log.info("mappingConsumes");

    return "ok";
}
  • HTTP 요청의 Content-Type 헤더를 기반으로 미디어 타입으로 매핑.
  • 만약 맞지 않으면 HTTP 415 상태코드(Unsupported Media Type)을 반환.
  • consume 예시.
consumes = "text/plain"
consumes = {"text/plain", "application/*"}
consumes = MediaType.TEXT_PLAIN_VALUE

미디어 타입 조건 매핑 - HTTP 요청 Accept, produce

/**
 * Accept 헤더 기반 Media Type
 * produces = "text/html"
 * produces = "!text/html"
 * produces = "text/*"
 * produces = "*\/*"
 */
@PostMapping(value = "/mapping-produce", produces = "text/html")
public String mappingProduces() {
    log.info("mappingProduces");

    return "ok";
}
  • HTTP 요청의 Accept 헤더를 기반으로 미디어 타입으로 매핑.
  • 만약 맞지 않으면 HTTP 406 상태코드(Not Acceptable)을 반환.
produces = "text/plain"
produces = {"text/plain", "application/*"}
produces = MediaType.TEXT_PLAIN_VALUE
produces = "text/plain;charset=UTF-8"

## 요청 매핑 - API 예시.

  • 회원 관리를 HTTP API로 만든다 생각하고 매핑을 어떻게 하는지 확인. (실제 데이터 넘어가는 부분은 생략)

회원 관리

  • API 회원 목록 조회 : GET /users
  • 회원 등록 : POST /users
  • 회원 조회 : GET /users/{userId}
  • 회원 수정 : PATCH /users/{userId}
  • 회원 삭제 : DELETE /users/{userId}
package hello.springmvc.basic.requestmapping;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/mapping/users")
public class MappingClassController {

    /**
     *  회원 목록 조회 : GET '/users'
     *  회원 등록   : POST '/users'
     *  회원 조회   : GET '/users/{userId}'
     *  회원 수정   : PATCH '/users/{userId}'
     *  회원 삭제   : DELETE '/users/{userId}'
     * */
    @GetMapping
    public String user() {
        return "get users";
    }

    @PostMapping
    public String addUser() {
        return "post user";
    }

    @GetMapping("/{userId}")
    public String findUser(@PathVariable String userId) {
        return "get userId";
    }

    @PatchMapping("/{userId}")
    public String updateUser(@PathVariable String userId) {
        return "update userId=" + userId;
    }

    @DeleteMapping("/{userId}")
    public String delete(@PathVariable String userId) {
        return "update userId=" + userId;
    }
}
  • @RequestMapping("/mapping/users") 클래스 레벨에 매핑 정보를 두면 메서드 레벨에서 해당 정보를 조합해서 사용.
반응형

+ Recent posts