• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

상품 수정시 유효성 검사

23.03.14 20:37 작성 23.03.14 21:09 수정 조회수 422

0

상품 수정 기능 구현중에

수정내역의 유효성 검사를 추가해보고 싶어서 코드를 추가했습니다.

```java```
package jpabook.jpashopre.controller;

import lombok.Getter;
import lombok.Setter;

import javax.validation.constraints.NotEmpty;

@Getter
@Setter
public class BookForm {

    private Long id;
    @NotEmpty(message = "이름은 필수 입력 사항입니다.")
    private String name;
    private int price;
    private int stockQuantity;
    @NotEmpty(message = "작가은 필수 입력 사항입니다.")
    private String author;
    private String isbn;
}


package jpabook.jpashopre.controller;

import jpabook.jpashopre.domain.item.Book;
import jpabook.jpashopre.domain.item.Item;
import jpabook.jpashopre.service.ItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequiredArgsConstructor
@Slf4j
public class itemController {

    private final ItemService itemService;

    @GetMapping("/items/new")
    public String createForm(Model model) {
        model.addAttribute("form", new BookForm());
        return "item/createItemForm";
    }

    @PostMapping("/items/new")
    public String create(@Valid @ModelAttribute("form") BookForm form, BindingResult result) {
        if(result.hasErrors()){
            return "item/createItemForm";
        }

        Book item = new Book();
        item.setName(form.getName());
        item.setPrice(form.getPrice());
        item.setStockQuantity(form.getStockQuantity());
        item.setAuthor(form.getAuthor());
        item.setIsbn(form.getIsbn());

        itemService.saveItem(item);

        return "redirect:/";
    }

    @GetMapping("/items")
    public String list(Model model) {
        List<Item> items = itemService.findItems();
        model.addAttribute("items", items);

        return "item/itemList";
    }

    @GetMapping("/items/{itemId}/edit")
    public String updateItemForm(@PathVariable("itemId") Long itemId, Model model) {
        Book item = (Book) itemService.findOne(itemId);

        BookForm form = new BookForm();
        form.setId(item.getId());
        form.setName(item.getName());
        form.setPrice(item.getPrice());
        form.setStockQuantity(item.getStockQuantity());
        form.setAuthor(item.getAuthor());
        form.setIsbn(item.getIsbn());

        model.addAttribute("form", form);
        return "item/updateItemForm";
    }

    @PostMapping("/items/{itemId}/edit")
    public String updateItem(@ModelAttribute("form") @Valid BookForm form,@PathVariable("itemId")Long itemId, BindingResult result) {
        if (result.hasErrors()) {

            return "item/updateItemForm";
        }
       itemService.updateItem(form.getId(), form.getName(), form.getPrice(), form.getStockQuantity(), form.getAuthor(), form.getIsbn());
        return "redirect:/items";
    }

}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/header :: header" />
<style>
  .fieldError {
    border-color: #bd2130;
  }
</style>
<body>
<div class="container">
  <div th:replace="fragments/bodyHeader :: bodyHeader"/>
  <form th:object="${form}" method="post">
    <!-- id -->
    <input type="hidden" th:field="*{id}" />
    <div class="form-group">
      <label th:for="name">상품명</label>
      <input type="text" th:field="*{name}" class="form-control"
             placeholder="이름을 입력하세요"
             th:class="${#fields.hasErrors('name')}? 'form-control fieldError' : 'form-control'">
      <p th:if="${#fields.hasErrors('name')}"
         th:errors="*{name}">Incorrect date</p>
    </div>
    <div class="form-group">
      <label th:for="price">가격</label>
      <input type="number" th:field="*{price}" class="form-control"
             placeholder="가격을 입력하세요" />
    </div>
    <div class="form-group">
      <label th:for="stockQuantity">수량</label>
      <input type="number" th:field="*{stockQuantity}" class="form-control" placeholder="수량을 입력하세요" />
    </div>
    <div class="form-group">
      <label th:for="author">저자</label>
      <input type="text" th:field="*{author}" class="form-control"
             placeholder="저자를 입력하세요"
             th:class="${#fields.hasErrors('author')}? 'form-control fieldError' : 'form-control'">
      <p th:if="${#fields.hasErrors('author')}"
         th:errors="*{author}">Incorrect date</p>
    </div>
    <div class="form-group">
      <label th:for="isbn">ISBN</label>
      <input type="text" th:field="*{isbn}" class="form-control"
             placeholder="ISBN을 입력하세요" />
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
  <div th:replace="fragments/footer :: footer" />
</div> <!-- /container -->
</body>
</html>

이름을 입력하지 않고 유효성검사를 실시했습니다. 하지만...

네...실패했습니다

네트워크에서도 이름이 빠진채로 의도대로 전달도 되었으나 뷰를 표기하지 못하고 화이트라벨 에러페이지만 나옵니다 ㅠ

콘솔도 의도된 에러메시지가 출력이 됩니다.

  1. 뷰단쪽에 문제 일까요? 해결

th:action="@{/items/*{id}/edit}"

->updateItemForm,html에 form에 action으로 해결하였습니다.

  1. 화이트라벨 에러페이지가 좀더 상세한 에러메시지를보여줬으면 하는데 어떻게 설정해야 할까요?

답변 1

답변을 작성해보세요.

2

OMG님의 프로필

OMG

2023.03.15

안녕하세요. 하리보님, 공식 서포터즈 OMG입니다.
.

스프링부트의 whitelabel error page 에서 추가로 상세한 정보를 알 수 있는 방법은 없는 것으로 알고 있습니다.

에러페이지의 에러코드와 콘솔이나 api응답의 내용으로 원인일 파악해야 할 것 같아요.

간혹 아래와 같이 상세 내용이 페이지에 나와있는 경우가 있지만 콘솔이나 응답에서도 확인하실 수 있는 내용입니다.

image
.
감사합니다.

하리보님의 프로필

하리보

질문자

2023.03.15

감사합니다!