📗 스프링 Spring

[스프링/Spring] Interceptor

핑크빛연어 2021. 5. 17. 17:54

 

Interceptor

Interceptor 는 AOP 의 개념을 적용한 Spring MVC 의 요소

요청 주소에 대해 관심을 갖고 요청이 발생하게 되면 요청 주소를 확인하여 Controller 의 메서드를 호출하기 전이나 후에 다른 메서드를 호출 할 수 있도록 가로채가는 개념

요청 발생 시 호출되는 메서드의 코드가 중복되는 부분이 있을 때 Interceptor 를 통해 처리하게 됨

로그인 여부확인, 등급별 서비스 사용권한 확인 등의 작업을 처리할 때 많이 사용

 

 

1.Interceptor 클래스 

 

HandlerInterceptor 를 implements(구현) 한 클래스를 만들어 메소드를 구현하거나,
HandlerInterceptorAdapter 를 extends(상속받는) 하는 클래스를 만들어 메서드를 구현하여 사용할 수 있습니다.

 

대표 메서드 3가지

preHandle() Controller 의 메서드가 호출되기 전 호출. 이 메서드가 false 를 반환하면 코드의 흐름이 중단됨(postHandle, afterCompletion 등 다음으로 넘어가지 않음)
postHandle() Controller 의 메서드가 호출되고 난 후 호출. View 처리를 수행하기 전에 호출
afterCompletion() View 처리까지 완료되고 응답결과가 브라우저로 전달되기 전에 호출

 

HandlerInterceptor 를 implements(구현) 한 Interceptor 클래스

package com.my.spring.interceptor;

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

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

public class TestInterceptor1 implements HandlerInterceptor {
	
	private String TAG = "===== "+TestInterceptor1.class.getSimpleName()+" >> ";

	/**
	 * Controller 의 메서드가 호출되기 전에 호출
	 * false 반환 시 요청 처리 진행이 중단됨
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println(TAG+"preHandle() "); 
		return HandlerInterceptor.super.preHandle(request, response, handler);
//		return false;
	}
	
	/**
	 * Controller 의 메서드가 호출되고 난 후 호출 
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println(TAG+"postHandle() ");
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	
	/**
	 * View 처리까지 완료되면 호출 
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println(TAG+"afterCompletion() ");
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
}

 

HandlerInterceptorAdapter 를 extends(상속받는) 하는 클래스

package com.my.spring.interceptor;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class TestInterceptor2 extends HandlerInterceptorAdapter {
	
	private String TAG = "===== "+TestInterceptor2.class.getSimpleName()+" >> ";

	/**
	 * Controller 의 메서드가 호출되기 전에 호출
	 * false 반환 시 요청 처리 진행이 중단됨
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println(TAG+"preHandle() ");
		return super.preHandle(request, response, handler);
	}
	
	/**
	 * Controller 의 메서드가 호출되고 난 후 호출 
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println(TAG+"postHandle() ");
		super.postHandle(request, response, handler, modelAndView);
	}
	
	/**
	 * View 처리까지 완료되면 호출 
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println(TAG+"afterCompletion() ");
		super.afterCompletion(request, response, handler, ex);
	}
	

}

 

 

2. Java 로 Spring MVC 설정 Interceptor 세팅 

 

ServletAppContext.java - Interceptor 등록

	/**
	 * Interceptor 등록 
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		
		WebMvcConfigurer.super.addInterceptors(registry);
		
		TestInterceptor1 interceptor1 = new TestInterceptor1();
		TestInterceptor2 interceptor2 = new TestInterceptor2();
		TestInterceptor3 interceptor3 = new TestInterceptor3();
		TestInterceptor4 interceptor4 = new TestInterceptor4();
		TestInterceptor5 interceptor5 = new TestInterceptor5();
		TestInterceptor6 interceptor6 = new TestInterceptor6();
		TestInterceptor7 interceptor7 = new TestInterceptor7();
		TestInterceptor8 interceptor8 = new TestInterceptor8();
		
		InterceptorRegistration reg1 = registry.addInterceptor(interceptor1);
		InterceptorRegistration reg2 = registry.addInterceptor(interceptor2);
		InterceptorRegistration reg3 = registry.addInterceptor(interceptor3);
		InterceptorRegistration reg4 = registry.addInterceptor(interceptor4);
		InterceptorRegistration reg5 = registry.addInterceptor(interceptor5);
		InterceptorRegistration reg6 = registry.addInterceptor(interceptor6);
		InterceptorRegistration reg7 = registry.addInterceptor(interceptor7);
		InterceptorRegistration reg8 = registry.addInterceptor(interceptor8);
		
		reg1.addPathPatterns("/test01");  //관심사를 등록해준다 (요청주소 등록)
		reg2.addPathPatterns("/test01");  //관심사를 등록해준다 (요청주소 등록)
		reg3.addPathPatterns("/test02");  //관심사를 등록해준다 (요청주소 등록)
		
//		reg4.addPathPatterns("/test01");  //관심사를 등록해준다 (요청주소 등록)
//		reg4.addPathPatterns("/test02");  //관심사를 등록해준다 (요청주소 등록)
		reg4.addPathPatterns("/test01", "/test02");  //관심사를 여러개 등록해준다 (요청주소 등록)
		
		reg5.addPathPatterns("/sub01/test03", "/sub01/test04");  //관심사를 여러개 등록해준다 (하위 요청주소 등록)
		
		reg6.addPathPatterns("/*");
		
		reg7.addPathPatterns("/sub01/*");

		//모든 요청주소를 요청할 때 마다 등록
		reg8.addPathPatterns("/**");  //관심사 등록
		
		reg8.excludePathPatterns("/*");  //제외할 주소 등록 
	}

 

pattern
* : 이름 하나를 의미하며 글자수, 글자 등 제한이 없습니다.
? : 글자하나를 의미
** : 하위 이름까지 포함하여 글자수, 글자 등 제한이 없습니다.

 

 

3. xml 로 Spring MVC 설정 Interceptor 세팅 

 

Interceptor 클래스는 Java 세팅에 사용하는 클래스와 동일합니다.

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
			 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			 xmlns:beans="http://www.springframework.org/schema/beans"
			 xmlns:context="http://www.springframework.org/schema/context"
			 xsi:schemaLocation="http://www.springframework.org/schema/mvc
			 					 http://www.springframework.org/schema/mvc/spring-mvc.xsd
			 					 http://www.springframework.org/schema/beans
			 					 http://www.springframework.org/schema/beans/spring-beans.xsd
			 					 http://www.springframework.org/schema/context
			 					 http://www.springframework.org/schema/context/spring-context.xsd">
			 					 
	...
	
	<!-- Interceptor 들을 Bean 으로 등록 -->
	<beans:bean class="com.my.spring.interceptor.TestInterceptor1" id="inter1"/>
	    <interceptors>
	        <interceptor>
	            <mapping path="/test01"/>
	            <beans:ref bean="inter1"/>
	        </interceptor>
	        <interceptor>
	            <mapping path="/test02"/>
	            <beans:ref bean="com.my.spring.interceptor.TestInterceptor2"/> <!-- TestInterceptor2 는 test02 만 등록 -->
	        </interceptor>
	        <interceptor>
	            <mapping path="/test02"/>
	            <beans:ref bean="inter1"/>
	        </interceptor>
	        <interceptor>
	            <mapping path="**"/>
	            <exclude-mapping path="/*"/> <!-- 제외할 주소 등록 -->
	            <beans:ref bean="com.my.spring.interceptor.TestInterceptor3"/>
	        </interceptor>
	    </interceptors>
	    
</beans:beans>

 

 

728x90
반응형