崛起於Springboot2.X + 180秒配置攔截器(21)

《SpringBoot2.X心法總綱》      html

      序言:幾乎全部項目都須要攔截器,因此小夥伴們必需要掌握這門技術哦,否則只會mybaits增刪改查那是實習生乾的活呀。spring

一、建立攔截器類

public class MyIncerteptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("進入攔截器");

        HttpSession session = request.getSession();
        Admin user = (Admin) request.getSession().getAttribute("ADMIN_ACCOUNT");
        if (user == null) {
            //用戶爲空,從新登陸
            response.sendRedirect(request.getContextPath() + "/login.html");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

二、註冊攔截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        String[] addPathPatterns ={
                "/dtb/**"
        };
        String[] excludePathPatterns ={
                "/test/**"
        };
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new MyIncerteptor());
        interceptorRegistration.addPathPatterns(addPathPatterns);
        interceptorRegistration.excludePathPatterns(excludePathPatterns);
    }
}

addPathPatterns是攔截的那些目錄,excludePathPatterns不攔截的路徑,上面咱們能夠換一種經常使用的寫法,只不過上面看上去更明白,interceptorRegistration獲取的註冊對象添加攔截器,並設置攔截路徑springboot

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        String[] addPathPatterns ={
                "/dtb/**"
        };
        String[] excludePathPatterns ={
                "/test/**"
        };
       registry.addInterceptor(new MyIncerteptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
    }
}

 在優化一下,能夠寫成:session

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        
       registry.addInterceptor(new MyIncerteptor()).addPathPatterns("/dtb/**").excludePathPatterns("/test/**");
    }
}

成功!其實就兩個類就能夠了。ide

三、注意點:

        springboot2.0之後:使用spring5,廢棄了WebMvcConfigurerAdapter,解決方案 implements WebMvcConfigurerpost

        springboot2.0以前,1.X版本,使用spring4,使用攔截器須要 extends WebMvcConfigurerAdapter優化

相關文章
相關標籤/搜索