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
'Spring' 카테고리의 다른 글
| [스프링 부트]이미지데이터 스프링부트 비동기구현 (0) | 2023.02.22 |
|---|---|
| [스프링 부트] 파일 업로드 (0) | 2023.02.21 |
| [스프링 부트] REST API (1) | 2023.02.16 |
| [스프링 부트] 뷰 템플릿 실습 (0) | 2023.02.14 |
| [스프링 부트] 데이터베이스 연결 (2) | 2023.02.14 |