커피와 개발자

Interceptor 설정 본문

프로젝트/Spring Boot

Interceptor 설정

광박이 2022. 10. 11. 13:25
728x90

Interceptor 설정

인터셉터(Interceptor)란 컨트롤러에 들어오는 요청 HttpRequest와 컨트롤러가 응답하는 HttpResponse를 가로채는 역할을 합니다.
인터셉터는 관리자만 접근할 수 있는 관리자 페이지에 접근하기 전에 관리자 인증(권한)을 하는 용도로 활용될 수 있으며, 로그인이 필요한 페이지로 리다이렉트 보내야 하는 경우, 클라이언트 요청에 대한 공통적인 로깅, 공통적으로 처리해야 할 내용을 처리할 수도 있습니다.

인터셉터는 Servlet의 앞, 뒤에서 HttpRequest, HttpResponse을 가로채는 Filter와 그 역할은 유사하지만, Filter와 Interceptor는 서로 다른 것입니다.

Filter와 Interceptor의 차이 :

  • 호출 시점 : Filter는 DispatcherServlet이 실행되기 전, Interceptor는 DispatcherServlet이 실행된 후
  • 설정 위치 : Filter는 web.xml, Interceptor는 spring-servlet.xml
  • 구현 방식 : Filter는 web.xml에서 설정을 하면 구현이 가능하지만, Interceptor는 설정은 물론 메서드 구현이 필요합니다.

Interceptor 적용 :

interceptor 디렉터리를 추가하고, LoggerInterceptor.java 파일을 작성합니다.

HandlerInterceptor 인터페이스를 상속받으면, 3개의 메서드를 오버라이드 합니다.

  • preHandle : 클라이언트의 요청을 컨트롤러에 전달하기 전에 호출됩니다. 여기서 false를 리턴하면 다음 컨트롤러(Controller)를 실행하지 않습니다.
  • postHandle : 클라이언트의 요청을 처리한 뒤에 호출됩니다. 컨트롤러에서 예외가 발생되면 실행되지 않습니다.
  • afterCompletion : 클라이언트 요청을 마치고 클라이언트에서 뷰를 통해 응답을 전 송한 뒤 실행이 됩니다. 뷰를 생성할 때에 예외가 발생할 경우에도 실행이 됩니다.

Interceptor 설정 적용 :

configuration 디렉터리를 추가하고, WebConfiguration.java 파일을 작성합니다.

결과 확인 : 

http://localhost:9090/sample 접속 후 로그 확인

2022-05-21 21:45:35,863 [INFO ] [http-nio-9090-exec-1] s.p.s.c.i.LoggerInterceptor: /********** BEGIN **************************************************
2022-05-21 21:45:35,864 [INFO ] [http-nio-9090-exec-1] s.p.s.c.i.LoggerInterceptor:  * Request URI : /sample
2022-05-21 21:45:35,899 [DEBUG] [http-nio-9090-exec-1] s.p.s.s.c.SampleController: SampleController.page debug log
2022-05-21 21:45:35,899 [INFO ] [http-nio-9090-exec-1] s.p.s.s.c.SampleController: SampleController.page info log
2022-05-21 21:45:35,910 [INFO ] [http-nio-9090-exec-1] s.p.s.c.i.LoggerInterceptor:  *********** END ***************************************************/

※ SpringBoot 과거 버전에서는 HandlerInterceptorAdapter을 extends 하거나 HandlerInterceptor를 implements 해서 구현했는데, Spring 5.3을 사용하는 SpringBoot 2.4 버전부터는 HandlerInterceptorAdapter이 Deprecated 되었습니다. 이에 HandlerInterceptor 또는 AsyncHandlerInterceptor를 implements 해서 구현해야 하는데, 비동기 요청까지 후처리까지 지원하면 afterConcurrentHandlingStarted 메서드가 포함된 AsyncHandlerInterceptor를 implements 해야 합니다.

 

728x90

'프로젝트 > Spring Boot' 카테고리의 다른 글

DataBase 연동 (MariaDB, HikariCP)  (0) 2022.10.11
Argument Resolver 설정  (0) 2022.10.11
jsonView 설정  (0) 2022.10.11
AOP(Aspect Oriented Programming) 설정  (0) 2022.10.11
log4j2 설정  (0) 2022.10.11
Comments