SpringBoot-拦截器的使用

2022/7/5 23:21:25

本文主要是介绍SpringBoot-拦截器的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

  • 定义-Inteceptor

  • 使用:以用户登录,注册...为例
    创建拦截器类,实现HandlerInterceptor接口,重写preHandle方法,在该方法中编写业务拦截的规则

    创建LoginInceptor,实现HandlerInterceptor

    public class LoginInterceptor implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //判断session是否存在id HttpSession session = request.getSession(); if (session.getAttribute("id")==null) { //null,没有登录 response.sendRedirect("../user/login.do"); return false; }else { return true; } } }

  • 创建拦截器配置类
    使用@Configuration注解将这个类定义为配置类,实现WebMvcConfigurer接口并且重写addInterceptors方法

public class InterceptorConfig implements WebMvcConfigurer{ @Override public void addInterceptors(InterceptorRegistry registry) { //黑名单 List<String> addPathPatterns = new ArrayList<String>(); addPathPatterns.add("/user/**.do"); //白名单 List<String> excludePathPatterns = new ArrayList<>(); excludePathPatterns.add("/user/login.do"); excludePathPatterns.add("/user/reg.do"); //拦截器类 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns(addPathPatterns) .excludePathPatterns(excludePathPatterns); } }



这篇关于SpringBoot-拦截器的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程