인터셉터(Interceptor)란?
말 그대로 "어떤것을 가로챈다" 라는 뜻이다.
컨트롤러로 들어오는 요청(메서드(URI))에 접근하는 과정에서 무언가를 제어할 필요가 있을 때 사용이 된다.
정확히는 컨트롤러에 접근하기 전과 후로 나뉜다.
Filter와의 차이점?
인터셉터보다 필터가 먼저 동작한다.
인터셉터는 필터와 다르게 메서드로 제어를 한다.
- Interceptor클래스 → 메서드로 제어를 하기 위한 클래스 파일
- InterceptorConfig클래스 → 어떤 URI에 대해서 동작할 것인지 설정을 위한 클래스 파일
PostViewLogInterceptor.java
package com.example.interceptor.interceptor;
import jakarta.servlet.http.*;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.*;
@Slf4j
@Component
public class PostViewLogInterceptor implements HandlerInterceptor {
@Override
public void postHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
String uri = request.getRequestURI();
String postId = Integer.parseInt(uri.split("/")[2]) > 0 ? uri.split("/")[2] : "알수없음";
// 접속 URI - request.getRequestURI();
String ip = request.getRemoteAddr();
// ip 주소 확인 - request.getRemoteAddr();
// 현재 시각 확인 - LocalDateTime.now();
LocalDateTime now = LocalDateTime.now();
log.info("게시글 조회 - ID: {}, IP: {}, 시각: {}", postId, ip, now);
}
}
이 메서드는 컨트롤러 메서드가 실행된 후에 실행되는 인터셉터 단계인것이다.
메서드로 제어하기 위한 인터셉터 클래스를 생성했다.
HandlerInterceptor를 상속받아서 특정HTTP요청 처리 이후에 로그를 남기는 역할을 수행한다.
요청 URI를 받아서 마지막단 / 경로의 길이가 2보다 크면 uri의 값을 반환하고 2보다 작으면 "알수 없음"이라고 반환한다.
ip요청 메서드 getRemoteAddr로 ip주소를 받아온다.
InterceptorConfig.java
package com.example.interceptor.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import com.example.interceptor.interceptor.PostViewLogInterceptor;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private PostViewLogInterceptor postviewloginterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 인터셉터 등록
registry.addInterceptor(postviewloginterceptor)
.addPathPatterns("/post/*");
WebMvcConfigurer.super.addInterceptors(registry);
}
}
이미 빈으로 등록된 PostViewLogInterceptor를 @Autowired로 가져와서
WebMvcConfigurer에 연결하여 활성화 시킨다.
InterceptorConfig클래스는 WebMvcConfigurer를 구현하여 SpringMVC의 설정을 커스터마이징한다.
InterceptorRegistry의 addInterceptor로 postviewloginterceptor를 MVC요청 파이프라인에 등록한다.
"/post/*"를 사용하여 해당 인터셉터가 /post/로 시작하는 URL패턴에 대해서만 동작하도록 연결한다.
PostController.java
package com.example.interceptor.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/post")
public class PostController {
@GetMapping("/{id}")
public String viewPost(@PathVariable Long id) {
return "게시글 ID: " + id;
}
}
그럼 이 컨트롤러를 실행시켜보자
만약 0이라는 값을 받으면
로그에 알수 없음 이라고 찍히는 것을 볼 수 있다.
그럼 인터셉터의 사용 이유는 뭘까?
Spring MVC에서 인터셉터(HandlerInterceptor)를 사용하는 가장 큰 이유는 요청 처리 과정에서 컨트롤러의 핵심 로직 실행 전/후에 공통적으로 수행해야 하는 부가적인 작업(횡단 관심사)들을 분리하여 처리하기 위해 사용된다.
위의 예시처럼 로그를 찍는 역할이 아닌 권한이나 로그인 여부 값을 불러올 때도 유용하게 사용이 된다고 한다.
게시글에서 작성자만 수정권한을 가질 때 DB와 연결하여 HTTP요청을 보낸 값과 비교를 하여
권한을 통과시킬지 안시킬지 결정을 할 수 있다.
'Spring' 카테고리의 다른 글
스프링부트 - 파일 업로드 (0) | 2025.05.10 |
---|---|
스프링부트 - 필터(FilterRegistrationBean) (0) | 2025.05.10 |
[스프링부트] - Controller Advice (1) | 2025.05.07 |
[스프링부트] - AOP에 대해서 알아보자 (0) | 2025.05.07 |
[스프링부트] - Model 객체 (0) | 2025.05.06 |