• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Errors나 BindingResult 사용시 주의할점이 있습니다.

20.08.09 03:02 작성 조회수 4.51k

9

디버그와 원인을 찾는데 꽤 많은 시간이 들어 혹시 제가 겪었던 상황과 비슷한 일을 겪는 분이 계실 것 같아 적었습니다.

스터디 생성시 이미 존재하는 path 요청을 날렸는데 제가 생각했던 대로 동작을 하지 않았습니다.

제가 예상했던 동작은 validator를 통해 이미 존재하는 경우 errors.rejectValue()로 필드에 에러코드를 추가하였으니 Post요청시 에러가 존재하니 study/form를 보여주고 

등록 화면에서는 validator에서 적어준 메세지가 보여야 한다 였는데 예상과는 다르게 whitelabel 에러 페이지와 함께  BindException 발생하였습니다.

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors

디버그를 해봐도 validator에서 에러코드 추가까지는 정상 동작하는데 post에서 break point로 잡히지 않았습니다.

영상을 시청하기 전에 코드를 작성하여 잘못 구현하였나 싶어 완성된 코드와 비교해보니 post요청에서 Model 인스턴스를 파라미터로 선언할 때 Errors보다 먼저 선언한 것을 발견하였습니다.

@PostMapping("/new-study")
public String newStudySubmit(@CurrentUser Account account, @Valid StudyForm studyForm, Model model,Errors errors) {
if (errors.hasErrors()) {
model.addAttribute(account);
return "study/form";
}
// 새 스터디 등록 후 redirect...
}

@PostMapping("/new-study")
public String newStudySubmit(@CurrentUser Account account, @Valid StudyForm studyForm, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute(account);
return "study/form";
}
// 새 스터디 등록 후 redirect...
}

그래서 파라미터의 순서에 영향을 받는다고 하고 넘어가려다 스프링 레퍼런스를 찾아보고 확실히 할 수 있었습니다.

Errors, BindingResult : For access to errors from validation and data binding for a command object (that is, a @ModelAttribute argument) or errors from the validation of a @RequestBody or @RequestPart arguments. You must declare an Errors, or BindingResult argument immediately after the validated method argument.

https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-arguments

답변 1

답변을 작성해보세요.

7

네 말씀하신대로 BindingResult나 Errors는 바인딩 받는 객체 바로 다음에 선언해야 합니다. 스프링 MVC 강좌에서 설명드렸는데 아마 이 강의부터 듣고 계신거 같네요. 이런식으로 이론을 채워 나가는 학습 방법도 좋은 방법입니다. 공유해 주셔서 감사합니다.