본문 바로가기

프로그래밍/Spring

[Spring] 인터셉터를 이용해 로그인 상태 체크 하기

[1] WebMvcConfigurer을 상속받은 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
 
    @Autowired
    private MyInterceptor myInterceptor;
 
    //로그인 체크 페턴
    private String[] includedUrlPatterns = {
            "/mypage/**"
    };
 
    //로그인 체크 예외
    private String[] excludedUrlPatterns = {
            //필요시 추가
    };
 
    /*
     * interceptor 설정
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(myInterceptor)
                .addPathPatterns(Arrays.asList(includedUrlPatterns))
                .excludePathPatterns(Arrays.asList(excludedUrlPatterns))
        ;
    }
 
    /*
     * Swagger 설정
     */
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/""classpath:/resources/",
            "classpath:/static/""classpath:/public/" };
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);    //기존 설정 반영
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
 
}
cs

 

[2] myInterceptor 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Component
@Slf4j
public class myInterceptor extends HandlerInterceptorAdapter {
 
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO : 작성
        return true;
    }
 
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //TODO : 작성
    }
}
cs