崛起于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优化

相关文章
相关标签/搜索