공부기록/Spring

Spring MVC3 - Error검증

jhs0129 2022. 1. 17. 19:54
320x100
반응형

에러 검증

Validator

컨트롤러에서 아래 검증기를 호출을 하여 만약 에러가 있다면 특정 페이지로 이동 혹은 다시 페이지 호출 등 행동을 취할 수 있다.

public class ItemValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public void validate(Object target, Errors errors) {
        //검증 로직
        /*
        * 아이디 공백이 아닌지
        * 비밀번호 공백이 아닌지
        * 정확한 값 타입이 입력이 되었는지 등등
        * 필요한 검증 로직 들어가면 됨
        */
    }
}

BindingResult, Errors

BindingResult는 Errors를 상속을 받음

간단한 공백이나 null값에 대한 처리는 ValidationUtils객체를 이용하여 간단하게 적용을 할 수 있다.

ex) ValidationUtils.rejectIfEmptyOrWhiteSpace(errors, "item", "itemName");

{
    if (item.getQuantity() == null || item.getQuantity() >= 9999) {
        bindingResult.rejectValue("quantity", "max", new Object[]{9999}, null);
    }

    if (item.getPrice() != null && item.getQuantity() != null) {
        int resultPrice = item.getPrice() * item.getQuantity();
        if(resultPrice < 10000){
            bindingResult.reject("totalPriceMin", new Object[]{10000, resultPrice}, null);
        }
    }

    if(bindingResult.hasErrors()){
        return "validation/v2/addForm";
    }
}

reject() vs rejectValue()

  • reject(): 글로벌 에러 추가
  • rejectValue(): 필드 에러 추가

Error 메세지

앞서 메세지 작성과 같은 방법으로 properties파일을 작성을 하면 된다

 

320x100

글로벌 메세지 코드

  • 에러코드 + "." + 객체 이름
  • 에러코드

필드 메세지 코드

  • 단일 필드 일 경우
    • 에러코드 + "." + 객체 이름 + "." + 필드 명
    • 에러코드 + "." + 필드 명
    • 에러코드 + "." + 필드 타입
    • 에러코드
  • List와 같이 목록인 경우
    • 에러코드 + "." + 객체 이름 + "." + 필드 명[인덱스].중첩필드명
    • 에러코드 + "." + 객체 이름 + "." + 필드 명.중첩필드명
    • 에러코드 + "." + 필드 명[인덱스].중첩필드명
    • 에러코드 + "." + 필드 명.중첩필드명
    • 에러코드 + "." + 중첩필드명
    • 에러코드 + "." + 필드 타입
    • 에러코드

뷰 출력

  • Spring tag사용
<form:form commandName="item"><!--html form태그 대신 사용 item객체 정보 지정-->
    <form:errors element="div"/>
    <form:errors path="email"><!--email 프로퍼티와 관련된 에러코드 존재시 메시지 출력-->
</form:form>
  • thymeleaf에서 사용
    <div>
      <label for="itemName" th:text="#{label.item.itemName}">상품명</label>
      <input type="text" id="itemName" th:field="*{itemName}"
              class="form-control" th:errorclass="field-error"
              placeholder="이름을 입력하세요">
      <div class="field-error" th:errors="*{itemName}"> 상품명 오류 </div>
      <!--에러 메세지 출력 item.itemName-->
    </div>

    기타

InitBinder

컨트롤러가 시작할때 검증기 미리 등록

@InitBinder
public void init(WebDataBinder dataBinder){
    dataBinder.addValidators(itemValidator);
}

public String addItem (@Validated @ModelAttribute Item item){
    /*
    *@Validated 어노테이션덕분에 
    *검증기의 validate실행 자동
    */
}

참고

인프런_스프링 MVC 2편 - 백엔드 웹개발 핵심 기술_김영한 님 강의
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2/dashboard

 

스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - 인프런 | 강의

웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습할 수 있

www.inflearn.com

 

320x100
반응형