카테고리 없음

클래스를 올바르게 검증하는 방법

기록만이살길 2021. 2. 28. 17:55
반응형

클래스를 올바르게 검증하는 방법

1. 질문(문제점):

주소 등록을위한 간단한 수업이 있습니다

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ColorDto {
    @Size(min = 2, max = 100, message = "The size must be in the range 2 to 100")
    private String colorName;
}

내 양식에서이 클래스의 개체와 데이터베이스에 이미있는 모든 엔터티를 추가합니다.

List<ColorDto> colors = colorService.getAll();
        model.addAttribute("colors", colors);
        model.addAttribute("colorForm", new ColorDto());
        return "color";

양식 자체는 다음과 같습니다.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Colors</title>
</head>
<body>
<h2>Colors</h2>
<div th:each="color : ${colors}">
    <p>
        Name : <span th:text="*{color.colorName}"></span>
    </p>
</div>
<h4>Add new color</h4>
<div>
    <form th:method="POST" th:action="@{/product/color}" th:object="${colorForm}">
        <tr>
            <td>Enter color:</td>
            <td><input type="text" th:field="*{colorName}" required/></td>
            <div th:if="${colorError}">
                <div style="color: red" th:text="${colorError}"></div>
            </div>
            <div style="color:red" th:if="${#fields.hasErrors('colorName')}" th:errors="*{colorName}" >color error</div>
        </tr>
        <tr>
            <td><input name="submit" type="submit" value="submit" /></td>
        </tr>
    </form>
</div>
<p><a href="/">Home</a></p>
</body>
</html>

이 양식의 데이터를 다음 방법으로 처리합니다.

@PostMapping("/color")
    public String addNewColor(@ModelAttribute("colorForm") @Valid ColorDto colorDto,
                              HttpSession httpSession,
                              BindingResult bindingResult,
                              Model model){
        if (bindingResult.hasErrors()) {
            return "color";
        }

필드를 올바르게 채우면 방법이 작동합니다. 잘못된 데이터를 보내면 프로그램이이 데이터를 처리하지 않습니다. 즉, 메소드에 전혀 들어 가지 않고 Http Status 400이 발행됩니다.

2. 해결방안:

addNewColor함수 에서 매개 변수의 순서를 변경 bindingResult하여 유효성이 검증 된 매개 변수 바로 뒤에 있도록 할 수 있습니까?

이렇게 :

    @PostMapping("/color")
    public String addNewColor(HttpSession httpSession,
                              @ModelAttribute("colorForm") @Valid ColorDto colorDto,
                              BindingResult bindingResult,
                              Model model){
        if (bindingResult.hasErrors()) {
            return "color";
        }
65783833
반응형