Spring Boot + 攔截器

本篇提供兩種方法實作攔截器

方案一、實作HandlerInterceptor

1.實作HandlerInterceptor

package com.liongogo.interceptor;

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

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

@Component
public class LionGoGoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("1.攔截器:preHandle");
        // 通過才回傳true
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("2.攔截器:postHandle");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        System.out.println("3.攔截器:afterCompletion");
    }
}

2.實作WebMvcConfigurer

package com.liongogo.configuration;

import com.liongogo.interceptor.LionGoGoInterceptor;
import com.liongogo.interceptor.TracingInterceptor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
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;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    private LionGoGoInterceptor lionGoGoInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(lionGoGoInterceptor)
                // 所有路徑都攔截
                .addPathPatterns("/**")
                // 排除不用攔截的路徑
                .excludePathPatterns("/xxx/xxxx");
    }
}
方案二、@Aspect
package com.liongogo.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LionGoGoAspectJInterceptor {

    @Around("execution (* com.liongogo.controller..*.*(..))")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("開始 LionGoGoAspectJInterceptor");
        Object object = proceedingJoinPoint.proceed();
        System.out.println("結束 LionGoGoAspectJInterceptor");
        return object;
    }
}