Spring

[스프링 부트] 인터셉터 적용하기

heejin424 2023. 2. 23. 11:34
728x90

로그인이나 계정의 권한과 관련된 처리 등을 인터셉터를 이용해서 더욱 효율적으로 처리할 수 있습니다.

 

1.HandlerInterceptor를 implements 하여 인터셉터 구현하기

package com.simple.basic.util;

import org.springframework.web.servlet.HandlerInterceptor;

public class UserAuthHandler implements HandlerInterceptor{

   
}

 

2. intercepter클래스를 빈으로 등록하기

package com.simple.basic.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.simple.basic.controller.HomeController;
import com.simple.basic.util.UserAuthHandler;
import com.simple.basic.util.UserSuccessHandler;


@Configuration //개별적인 스프링 빈 설정 파일
public class WebConfig implements WebMvcConfigurer {

	
	//인터셉터 클래스 빈으로 등록
	@Bean
	public UserAuthHandler userAuthHandler() {
		return new UserAuthHandler();
	}
	@Bean
	public UserSuccessHandler userSuccessHandler() {
		return new UserSuccessHandler();
	}


}

 

3. alt + shift + s 단축키로 상속받은 WebMvcConfigurer 클래스 내부에 있는 메서드 활용하기 + v

 

4. preHandle()메서드 활용해서 인터셉터 실행 됐는지 확인하기

 

preHandle( )

 

컨트롤러의 메서드에 매핑된 특정 URI가 호출됐을 때 실행되는 메서드로,
컨트롤러를 경유(접근)하기 직전에 실행되는 메서드입니다.

우리는 사용자가 어떠한 기능을 수행했는지를 파악하기 위하여
해당 기능과 매핑된 URI 정보가 콘솔에 로그가 출력되도록 처리합니다.

package com.simple.basic.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

public class UserAuthHandler implements HandlerInterceptor{

   /*
    * 1. HandlerInterceptor를 상속받는다.
    * 
    * preHandle - 컨트롤러 진입전에 실행
    * postHandle - 컨트롤러 수행 후에 실행
    * aftercomplate - 화면으로 가기 직전에 수행
    * 
    * 2. 인터셉터 클래스를 bean으로 등록
    */
   
   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
         throws Exception {
      
      System.out.println("인터셉터 실행");
      
      return true; //컨트롤러 실행
   }
   
}

 

5.postHandle( )메서드 활용해서 화면으로 결과를 전달하기 전에 실행하기

postHandle( )

 

컨트롤러를 경유(접근) 한 후, 즉 화면(View)으로 결과를 전달하기 전에 실행되는 메서드입니다.

preHandle( )과는 반대로 요청(Request)의 끝을 알리는 로그가 콘솔에 출력되도록 처리합니다.

package com.simple.basic.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserSuccessHandler implements HandlerInterceptor{

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		//modelAndView는 컨트롤러에서 model에 담은 데이터도 확인가능
		System.out.println("포스트핸들러" + request.getRequestURI());
		
	}

	
}

 

6.  실행순서

preHandle -> controller -> postHandle

 

7. 인터셉터 추가함수를 사용해서 제한걸기 ( 인터셉터 설정 )

package com.simple.basic.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.simple.basic.controller.HomeController;
import com.simple.basic.util.UserAuthHandler;
import com.simple.basic.util.UserSuccessHandler;


@Configuration //개별적인 스프링 빈 설정 파일
public class WebConfig implements WebMvcConfigurer {

	
	//인터셉터 클래스 빈으로 등록
	@Bean
	public UserAuthHandler userAuthHandler() {
		return new UserAuthHandler();
	}
	@Bean
	public UserSuccessHandler userSuccessHandler() {
		return new UserSuccessHandler();
	}

	//WebMvcConfigurer클래스가 제공해주는 인터셉터 추가함수
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor( userAuthHandler() )
				.addPathPatterns("/user/*") //path경로 포함
				.excludePathPatterns("/user/login");//path경로 제외
		
		
		//경로별로 인터셉트를 다르게 등록
		//포스트 핸들러
		registry.addInterceptor( userSuccessHandler())
				.addPathPatterns("/user/*");
	}

}

 

728x90