拦截分为两部分的设置,如下:

LoginInterceptor类

package com.hcr.electric.interceptor;

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

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

@Component
public class LoginInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object
            o) throws Exception {
       // request.getSession().invalidate();
        //System.out.println(request.getSession().getAttribute("userSession"))

        ;
        // TODO 我这里是通过用户是否登陆进行拦截,我的用户信息存储在session中,名称为userSession,大家可以自行实现
        if (request.getSession().getAttribute("userSession") == null) {
            // 拦截至登陆页面
          // request.getRequestDispatcher("/#/user/login").forward(request, response);
            // false为不通过
            response.sendRedirect("/");
           /* System.out.println(request.getRequestURL() + "/");*/
            return false;
        }
        // true为通过
        return true;
    }

}

WebConfig

package com.hcr.electric.config;

import com.hcr.electric.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 需要拦截的路径
        /*String[] addPathPatterns = {
                "/busi_userplatform_sca/**"
        };*/
        //不需要拦截的路径

        //addPathPatterns()添加拦截路径
        //excludePathPatterns() 添加不拦截的路径
        //添加注册登录拦截器
        registry.addInterceptor(loginInterceptor).addPathPatterns("/busi_userplatform_sca/**").excludePathPatterns("/busi_userplatform_sca/selectCompanyInfo");
        registry.addInterceptor(loginInterceptor).addPathPatterns("/businessManagement/**");
        registry.addInterceptor(loginInterceptor).addPathPatterns("/credentialManagement/**");
        registry.addInterceptor(loginInterceptor).addPathPatterns("/busi-userplatform-wx-order/**");
        registry.addInterceptor(loginInterceptor).addPathPatterns("/sys_user/**");

    }
}

如此简单,一直在路上从未被超越。