SpringBoot 登陆拦截器

两个类

@Controller
@Component

public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final Log log = LogFactory.getLog(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Object userInfo = request.getSession().getAttribute("USER");
        //没有用户信息,直接跳转到登录页面
        if(userInfo==null){

            log.info("尚未登录,跳转到登录界面");
            response.sendRedirect(request.getContextPath()+"login.html");
            return false;
        }

        return true;
    }


}
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


    @Autowired
    LoginInterceptor loginInterceptor;

    final String[] notLoginInterceptPaths = {"/js/*" ,"/css/*","/img/*","/font/*","/home/*","/login.html"};

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns(notLoginInterceptPaths);

    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }


}
WebMvcConfig 类中,我们对特定路径文件不进行登录拦截 ,具体文件路径可看下文.

外置web 文件到jar 包之外.

  mvc:
    view:
      prefix: /
      suffix: .html

 # 静态文件外置
  resources:
     static-locations: file:///ngddos/deploy

发布了192 篇原创文章 · 获赞 254 · 访问量 76万+

猜你喜欢

转载自blog.csdn.net/yulei_qq/article/details/95448339