반응형
컨트롤러 전/후 처리를 위한 어노테이션 @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
반응형
'개발 > spring' 카테고리의 다른 글
[page] Serializing PageImpl instances as-is is not supported (0) | 2025.05.21 |
---|---|
open feign에서 401일 때 바디가 안 나올 경우 (0) | 2025.03.11 |
[atomikos] jta XID already exists (0) | 2025.02.26 |
[pageImpl] 기존이랑 똑같이 페이징 시 갑자기 경고가? EnableSpringDataWebSupport (1) | 2024.12.18 |
[mvc] pathVariable String -> enum으로 자동 변환해주는 법 (1) | 2024.12.09 |