반응형

컨트롤러 전/후 처리를 위한 어노테이션 @ControllerAdvice

  • 전처리: @InitBinder, @ModelAttribute
  • 후처리: @ExceptionHandler
@ControllerAdvice
public class GlobalControllerAdvice {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        //form-data, application/x-www-form-urlencoded에 적용
        //POST 요청에서 setter가 없어도 되게끔
        binder.initDirectFieldAccess(); // 컨트롤러 실행 전 바인딩 설정
    }

    @ModelAttribute
    public void addGlobalAttributes(Model model) {
        model.addAttribute("appName", "MyApp"); // 모든 뷰에 공통 속성 추가
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleAll(Exception ex) {
        return ResponseEntity.status(500).body("서버 에러 발생");
    }
}

순서

요청 수신
 ↓
@InitBinder
 ↓
@ModelAttribute
 ↓
@RequestMapping (실제 컨트롤러 메서드 실행)
 ↓
@ExceptionHandler (예외 발생 시)

 

참고로 

binder.initDirectFieldAccess();

 

  • @InitBinder는 주로 form-data, application/x-www-form-urlencoded에 적용된다.
  • JSON 요청이라면 @InitBinder는 영향이 없음
    • @RequestBody로 받는 JSON 요청은 WebDataBinder가 아니라 Jackson이 처리

 

728x90
반응형

+ Recent posts