SpringBoot 拦截器HandlerInterceptor的基本使⽤

1.配置HandlerInterceptor

@Component
public class InterceptorModel implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object userSession = request.getSession().getAttribute("user");
        //认证session,不存在则拦截通行
        if(userSession!=null){
           return true;
        }
        //未通过验证,跳转登录页
        response.addHeader("Access-Control-Allow-Origin",(登录页面path);
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.sendRedirect(登录页面path+?appkey=返回网页密钥+&redirectUrl=登录过后返回的地址);
        return false;
        
    }
}

2.配置拦截规则

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    private InterceptorModel interceptorModel;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册Interceptor拦截器,配置拦截规则
        InterceptorRegistration registration = registry.addInterceptor(interceptorModel);
        registration.excludePathPatterns(
                "/aaa/*",
                "/bbb",
                "/ccc");
        registration.addPathPatterns("/","/ddd/*");
        registration.addPathPatterns("/","/eee/*");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37778018/article/details/124627426