天天看點

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的其他功能

addInterceptors:攔截器
addViewControllers:頁面跳轉
addResourceHandlers:靜态資源
configureDefaultServletHandling:預設靜态資源處理器
configureViewResolvers:視圖解析器
configureContentNegotiation:配置内容裁決的一些參數
addCorsMappings:跨域
configureMessageConverters:資訊轉換器      
/**
 * 預設首頁的設定,當輸入域名是可以自動跳轉到預設指定的網頁
 */
@Override
public void addViewControllers(ViewControllerRegistry registry)
{
    registry.addViewController("/").setViewName("forward:" + indexUrl);
}