본문 바로가기

카테고리 없음

spring boot 로그인 interceptor





인터셉터(Interceptor)란 클라이언트로 부터 받은 

요청을 처리하는 과정에서 특정 로직을 사전에 실행하거나 후에 처리를 할 수 있도록 한다. 

 

인터셉터는 HandlerInterceptor 인터페이스를 구현하여 사용할 수 있다. 

 

 

  • preHandle(): 컨트롤러가 요청을 처리하기 전에 실행됩니다.
  • postHandle(): 컨트롤러가 요청을 처리한 후, 뷰가 렌더링되기 전에 실행됩니다.
  • afterCompletion(): 뷰가 렌더링된 이후에 실행됩니다. 예외 처리 등을 할 수 있습니다.

 

Interceptor 등록하는 방법 : (WebMvcConfigurer 사용)

인터셉터는 Spring에 등록해야 동작한다. 

 

WebMvcConfigurer 인터페이스를 구현하여 인터셉터를 등록할 수 있다. 

 

package com.example.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.example.interceptor.LoginInterceptor;

@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) {

// 인터셉터 등록 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/**") // 모든 경로에 대해 인터셉터 적용 .excludePathPatterns("/login", "/register", "/resources/**"); // 특정 경로는 제외 } }