springboot使用handlerintercpteradapter自定义拦截器

以用户登录拦截验证为例

1.创建一个自定义的登录拦截器LoginInterCeptor

//编程方法被调用之前

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getServletPath();
//验证session
Object username = request.getSession().getAttribute("username");
if(username !=null){
return true;
}
//如果为空就去登录
else {
response.sendRedirect("/user/login");
return false;
}
}

2.配置WebMvcConfigurer,将自定义类加入到配置中
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
private static final List<String> EXCLUDE_PATH= Arrays.asList("/","/css/**","/js/**","/img/**");
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置拦截所有请求
registry.addInterceptor(LoginInterCeptor()).addPathPatterns("/**"). excludePathPatterns(EXCLUDE_PATH);

}
@Bean
public LoginInterCeptor LoginInterCeptor(){

return new LoginInterCeptor();
}

}

 3.注意EXCLUDE_PATH

EXCLUDE_PATH常量为过滤器放行规则,如果改为

. excludePathPatterns("/static/**");是不生效的

4.还可以引入注解的方式
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
我用的第一种方式,注解方式就不多做赘述


posted @ 2020-06-22 17:40  大梦千年  阅读(556)  评论(0编辑  收藏  举报