SpringBoot 优雅的配置拦截器方式

沙海 2021年5月25日04:31:49Java评论45字数 4680阅读15分36秒阅读模式
摘要

速读摘要

速读摘要文章源自JAVA秀-https://www.javaxiu.com/25731.html

一定要加@Configuration这个注解,在启动的时候在会被加载。欢迎加入我的知识星球,一起探讨架构,交流源码。文章源自JAVA秀-https://www.javaxiu.com/25731.html

原文约 2982 | 图片 6 | 建议阅读 6 分钟 | 评价反馈文章源自JAVA秀-https://www.javaxiu.com/25731.html

SpringBoot 优雅的配置拦截器方式

点击关注 ? Java基基 文章源自JAVA秀-https://www.javaxiu.com/25731.html

收录于话题文章源自JAVA秀-https://www.javaxiu.com/25731.html

#Java基基文章源自JAVA秀-https://www.javaxiu.com/25731.html

103个文章源自JAVA秀-https://www.javaxiu.com/25731.html

点击上方“Java基基”,选择“设为星标”文章源自JAVA秀-https://www.javaxiu.com/25731.html

做积极的人,而不是积极废人!文章源自JAVA秀-https://www.javaxiu.com/25731.html

文章源自JAVA秀-https://www.javaxiu.com/25731.html

源码精品专栏文章源自JAVA秀-https://www.javaxiu.com/25731.html

 文章源自JAVA秀-https://www.javaxiu.com/25731.html

文章源自JAVA秀-https://www.javaxiu.com/25731.html

来源:my.oschina.net/bianxin/blog/2876640文章源自JAVA秀-https://www.javaxiu.com/25731.html

大家好,我是基基!文章源自JAVA秀-https://www.javaxiu.com/25731.html

SpringBoot 优雅的配置拦截器方式文章源自JAVA秀-https://www.javaxiu.com/25731.html

其实spring boot拦截器的配置方式和springMVC差不多,只有一些小的改变需要注意下就ok了。下面主要介绍两种常用的拦截器:文章源自JAVA秀-https://www.javaxiu.com/25731.html

一、基于URL实现的拦截器:

public class LoginInterceptor extends HandlerInterceptorAdapter{ /**     * 在请求处理之前进行调用(Controller方法调用之前)     * 基于URL实现的拦截器     * @param request     * @param response     * @param handler     * @return     * @throws Exception     */    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        String path = request.getServletPath();        if (path.matches(Const.NO_INTERCEPTOR_PATH)) {         //不需要的拦截直接过            return true;        } else {         // 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等            System.out.println("====================================");            return true;        }    }}

关键代码:path.matches(Const.NO_INTERCEPTOR_PATH 就是基于正则匹配的url。文章源自JAVA秀-https://www.javaxiu.com/25731.html

/** * @author  BianP * @explain 常量类 */public class Const {    public static final String SUCCESS = "SUCCESS";    public static final String ERROR = "ERROR";    public static final String FIALL = "FIALL";    /**********************对象和个体****************************/    public static final String SESSION_USER = "loginedAgent"; // 用户对象    public static final String SESSION_LOGINID = "sessionLoginID"; // 登录ID    public static final String SESSION_USERID = "sessionUserID"; // 当前用户对象ID编号    public static final String SESSION_USERNAME = "sessionUserName"; // 当前用户对象ID编号    public static final Integer PAGE = 10; // 默认分页数    public static final String SESSION_URL = "sessionUrl"; // 被记录的url    public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // 登录页验证码    // 时间 缓存时间    public static final int TIMEOUT = 1800;// 秒 public static final String ON_LOGIN = "/logout.htm"; public static final String LOGIN_OUT = "/toLogout";    // 不验证URL anon:不验证/authc:受控制的    public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*";}

二、基于注解的拦截器

①创建注解:文章源自JAVA秀-https://www.javaxiu.com/25731.html

/** * 在需要登录验证的Controller的方法上使用此注解 */@Target({ElementType.METHOD})// 可用在方法名上@Retention(RetentionPolicy.RUNTIME)// 运行时有效public @interface LoginRequired {}

②创建拦截器:文章源自JAVA秀-https://www.javaxiu.com/25731.html

public class AuthorityInterceptor extends HandlerInterceptorAdapter{  @Override  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {   // 如果不是映射到方法直接通过        if (!(handler instanceof HandlerMethod)) {            return true;        }        // ①:START 方法注解级拦截器        HandlerMethod handlerMethod = (HandlerMethod) handler;        Method method = handlerMethod.getMethod();        // 判断接口是否需要登录        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);        // 有 @LoginRequired 注解,需要认证        if (methodAnnotation != null) {            // 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等            System.out.println("====================================");            return true;        }        return true; }}

三、把拦截器添加到配置中,相当于SpringMVC时的配置文件干的事儿:文章源自JAVA秀-https://www.javaxiu.com/25731.html

/** * 和springmvc的webmvc拦截配置一样 * @author BIANP */@Configurationpublic class WebConfigurer implements WebMvcConfigurer {  @Override  public void addInterceptors(InterceptorRegistry registry) {        // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录        registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");        registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");  }  @Bean  public LoginInterceptor LoginInterceptor() {   return new LoginInterceptor();  }  @Bean  public AuthorityInterceptor AuthorityInterceptor() {   return new AuthorityInterceptor();  }}

1、一定要加@Configuration 这个注解,在启动的时候在会被加载。文章源自JAVA秀-https://www.javaxiu.com/25731.html

2、有一些教程是用的“WebMvcConfigurerAdapter”,不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter ,虽然还可以用,但是看起来不好。文章源自JAVA秀-https://www.javaxiu.com/25731.html

3、也有一些教程使用的WebMvcConfigurationSupport,我使用后发现,classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不生效。具体可以原因,大家可以看下源码因为:WebMvcAutoConfiguration上有个条件注解:文章源自JAVA秀-https://www.javaxiu.com/25731.html

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

所以还是建议使用WebMvcConfigurer, 其实springMVC很多东西,都可以搬到springboot中来使用,只需要把配置文件的模式,改成 对应@Configuration 类就好了。文章源自JAVA秀-https://www.javaxiu.com/25731.html

欢迎加入我的知识星球,一起探讨架构,交流源码。加入方式,长按下方二维码噢文章源自JAVA秀-https://www.javaxiu.com/25731.html

SpringBoot 优雅的配置拦截器方式文章源自JAVA秀-https://www.javaxiu.com/25731.html

已在知识星球更新源码解析如下:文章源自JAVA秀-https://www.javaxiu.com/25731.html

SpringBoot 优雅的配置拦截器方式文章源自JAVA秀-https://www.javaxiu.com/25731.html

SpringBoot 优雅的配置拦截器方式文章源自JAVA秀-https://www.javaxiu.com/25731.html

SpringBoot 优雅的配置拦截器方式文章源自JAVA秀-https://www.javaxiu.com/25731.html

SpringBoot 优雅的配置拦截器方式文章源自JAVA秀-https://www.javaxiu.com/25731.html

最近更新《芋道 SpringBoot 2.X 入门》系列,已经 20 余篇,覆盖了 MyBatis、Redis、MongoDB、ES、分库分表、读写分离、SpringMVC、Webflux、权限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能测试等等内容。文章源自JAVA秀-https://www.javaxiu.com/25731.html

提供近 3W 行代码的 SpringBoot 示例,以及超 4W 行代码的电商微服务项目。文章源自JAVA秀-https://www.javaxiu.com/25731.html

获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。文章源自JAVA秀-https://www.javaxiu.com/25731.html

文章源自JAVA秀-https://www.javaxiu.com/25731.html

文章有帮助的话,在看,转发吧。谢谢支持哟 (*^__^*)
文章源自JAVA秀-https://www.javaxiu.com/25731.html

阅读原文文章源自JAVA秀-https://www.javaxiu.com/25731.html

继续阅读
速蛙云 - 极致体验,强烈推荐!!!购买套餐就免费送各大视频网站会员!快速稳定、独家福利社、流媒体稳定解锁!速度快,全球上网、视频、游戏加速、独立IP均支持!基础套餐性价比很高!这里不多说,我一直正在使用,推荐购买:https://www.javaxiu.com/59919.html
weinxin
资源分享QQ群
本站是JAVA秀团队的技术分享社区, 会经常分享资源和教程; 分享的时代, 请别再沉默!
沙海
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定