Spring Boot Controller 에서 전체 파라메터 폼 클래스 유효성 검증

2023. 7. 5. 10:35웹개발/Spring Boot

728x90

컨트롤러에 WebDataBinder을 이용하여 파라메터로 넘어오는 폼 클래스의 유효성검증을 추가

 

    private final BoradFormValidator boardFormValidator;
    
    @InitBinder("boardForm")
    public void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.addValidators(boardFormValidator);
    }

해당 컨트롤러 상단에 선언을 해줍니다. 

 

@InitBinder("boardForm") 에서 boardForm의 이름으로 클래스를 찾아서 검증

    @GetMapping("/boardDetail")
    public String detail(Model model, BoardForm boardForm) {
        return "boardDetail";
    }

 

	@Component
	public class BoardFormValidator implements Validator {
		@Override
		public boolean supports(Class<?> clazz) {
			return true;
		}

		@Override
		public void validate(Object target, Errors errors) {
			if("BoardForm".equals(target.getClass().getSimpleName())){ // 검증하려는 클래스 이름으로 필터
				BoardForm boardForm = (BoardForm)target;
				if(boardForm.getGubunCode().equals(GubunCode.GUBUN2) && boardForm.getContent().isBlank()){
					errors.rejectValue("content", "invalid.content", new Object[] { boardForm.getContent() }, "구분을 컨텐츠 선택시 내용은 필수입니다.");
				}
			}
		}
     

	}

 

2023.07.04 - [웹개발/Spring Boot] - Spring Boot Validated 유효성 검증 그룹 설정

728x90
반응형