Spring - Bean Validation - Object Error

1. Bean Validation - ObjectError 처리

@ScriptAssert()를 사용하여 ObjectError를 처리할 수 있다.

@Getter
@NoArgsConstructor
@ScriptAssert(lang = "javascript", script = "_this.price * _this.quantity >= 10000",
		message = "총합이 10000원 넘게 입력해주세요")
public class Item {

    private Long id;

    @NotBlank
    private String itemName;

    @NotNull
    @Range(min= 1000, max= 1000000)
    private Integer price;

    @NotNull
    @Max(9999)
    private Integer quantity;
}

위의 코드와 같이 @ScriptAssert 어노테이션을 주고 script에 구현하고 싶은 검증 로직을 작성하면

위와 같이 검증 실패 시 ObjectError 메시지를 반환받을 수 있다.

하지만 실제로 사용하다 보면 제약도 많고 복잡하기 때문에 아래와 같이 자바 코드ObejectError를 처리하는 것을 권장한다.

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

출처 : 스프링 MVC 2편 : 백엔드 웹 개발 활용 기술

좋은 웹페이지 즐겨찾기