SpringBoot全局拦截器

Springboot2.0中如何实现拦截器

在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现 WebMvcConfigurer接口(推荐),方式二继承WebMvcConfigurationSupport类,具体实现可看这篇文章

通过实现WebMvcConfigurer来实现拦截器

需求:在一个多机构系统中实现用户所属机构被删除或禁用后不能再使用系统

定义一个拦截器

package com.yrt.framework.interceptor;
/**
 * @author :GuangxiZhong
 * @date :Created in 2022/9/20 16:56
 * @description:
 * @modified By:
 * @version: 1.0
 */
@Component
public class OrgStatusInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        ContextUserInfo curUserInfo = ServletUtils.getCurUserInfo();
        Company company = curUserInfo.getCompany();
        // 判断机构的状态是否正常
        Utils.assertNotEmpty(company, "您所在的机构不存在!");
        Utils.assertTrue(company.getCertification_status() == 2, "您所在机构未认证审核通过!");
        Utils.assertTrue(company.getIs_delete() != 1 && company.getStatus() != 0, "您所在的机构已被禁用或删除!");
        return true;
    }
}

把这个拦截器加入到拦截器链中

@Configuration
@AllArgsConstructor
public class OrgStatusConfigurer implements WebMvcConfigurer {
    
    

    private OrgStatusInterceptor orgStatusInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(orgStatusInterceptor);
    }
}

某些URL可能是不需要做限制的,可以过滤URL

registry.addInterceptor(orgStatusInterceptor).excludePathPatterns("/v1/comm/area/*","/doc.html/*");

WebMvcConfigurer的其他功能

我们只实现了WebMvcConfigurer接口的addInterceptors方法,还可以实现下面这些方法。

addInterceptors:拦截器
addViewControllers:页面跳转
addResourceHandlers:静态资源
configureDefaultServletHandling:默认静态资源处理器
configureViewResolvers:视图解析器
configureContentNegotiation:配置内容裁决的一些参数
addCorsMappings:跨域
configureMessageConverters:信息转换器

比如默认的首页配置

/**
 * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页
 */
@Override
public void addViewControllers(ViewControllerRegistry registry)
{
    
    
    registry.addViewController("/").setViewName("forward:" + indexUrl);
}

猜你喜欢

转载自blog.csdn.net/qq32933432/article/details/126957586
今日推荐