springboot1.x 和 springboot2.x 配置拦截器区别就在于注册拦截器的方式不同,springboot1.x 配置方法是:
public class WebAppConfig extends WebMvcConfigurerAdapter {
springboot2.x 配置方法是:
public class LoginConfigurer implements WebMvcConfigurer {
下面详细的介绍使用方法。
一、springboot1.x 配置方法
1、注册拦截器
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器,添加拦截路径和排除拦截路径
registry.addInterceptor(new InterceptorConfig()).addPathPatterns("user/**").excludePathPatterns("admin/login");
}
}
2、实现 实现 HandlerInterceptor 接口
public class InterceptorConfig implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
二、springboot2.x 配置方法
一、注册拦截器
@Configuration
public class LoginConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加一个拦截器,连接以/authorize为前缀的url路径
registry.addInterceptor(new LoginURLInterceptor()).addPathPatterns("/pageController/authorize/**");
}
}
2、实现 HandlerInterceptor 接口
public class LoginURLInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("访问了/pageController/loginPage路径。");
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 {
}
}
推荐阅读:Spring Cloud Alibaba
-
【Spring Cloud Alibaba】微服务基础知识篇 -
【Spring Cloud Alibaba】Nacos 分布式配置 -
【Spring Cloud Alibaba】Nacos 服务注册与发现 -
【Spring Cloud Alibaba】Dubbo 分布式服务调用 -
【Spring Cloud Alibaba】Sentinel 服务熔断和限流 -
【Spring Cloud Alibaba】Gateway 分布式网关 -
【Spring Cloud Alibaba】Boot Admin 端点监控 -
【Spring Cloud Alibaba】Ribbon 负载均衡器 -
【Spring Cloud Alibaba】Oauth2 授权认证服务 -
【Spring Cloud Alibaba】Mybatis Plus 持久层 -
【Spring Cloud Alibaba】Mybatis Plus 代码生成器 -
【Spring Cloud Alibaba】Seata 分布式事务 -
【Spring Cloud Alibaba】Sleuth + Zipkin 链路追踪 -
【Spring Cloud Alibaba】Swagger 聚合接口文档
微信公众号
原文始发于微信公众号(花海里):【SpringBoot学习】3、SpringBoot 多个版本配置简单的拦截器
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69662.html