https://my.oschina.net/bianxin/blog/2876640

https://cs.xieyonghui.com/java/55.html

其实spring boot拦截器的配置方式和springMVC差不多,只有一些小的改变需要注意下就ok了。下面主要介绍两种常用的拦截器:

一、基于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。

/**
* @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)).*";
}

二、基于注解的拦截器

①创建注解:

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

②创建拦截器:

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时的配置文件干的事儿:

/**
* 和springmvc的webmvc拦截配置一样
* @author BIANP
*/
@Configuration
public 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  这个注解,在启动的时候在会被加载。

2、有一些教程是用的“WebMvcConfigurerAdapter”,不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter  ,虽然还可以用,但是看起来不好。

3、也有一些教程使用的WebMvcConfigurationSupport,我使用后发现,classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不生效。具体可以原因,大家可以看下源码因为:WebMvcAutoConfiguration上有个条件注解:

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

所以还是建议使用WebMvcConfigurer, 其实springMVC很多东西,都可以搬到springboot中来使用,只需要把配置文件的模式,改成 对应@Configuration 类就好了。

Spring Boot 优雅的配置拦截器方式的更多相关文章

  1. Springboot 系列(六)Spring Boot web 开发之拦截器和三大组件

    1. 拦截器 Springboot 中的 Interceptor 拦截器也就是 mvc 中的拦截器,只是省去了 xml 配置部分.并没有本质的不同,都是通过实现 HandlerInterceptor ...

  2. spring boot 学习(十二)拦截器实现IP黑名单

    拦截器实现IP黑名单 前言 最近一直在搞 Hexo+GithubPage 搭建个人博客,所以没怎么进行 SpringBoot 的学习.所以今天就将上次的”?秒防刷新”进行了一番修改.上次是采用注解加拦 ...

  3. Spring Boot 配置拦截器方式

    其实spring boot拦截器的配置方式和springMVC差不多,只有一些小的改变需要注意下就ok了.下面主要介绍两种常用的拦截器: 一.基于URL实现的拦截器: public class Log ...

  4. Spring Boot使用过滤器和拦截器分别实现REST接口简易安全认证

    本文通过一个简易安全认证示例的开发实践,理解过滤器和拦截器的工作原理. 很多文章都将过滤器(Filter).拦截器(Interceptor)和监听器(Listener)这三者和Spring关联起来讲解 ...

  5. Spring Boot实践——三种拦截器的创建

    引用:https://blog.csdn.net/hongxingxiaonan/article/details/48090075 Spring中的拦截器 在web开发中,拦截器是经常用到的功能.它可 ...

  6. 【spring boot】在自定义拦截器中从request中获取json字符串

    又这样的需求,需要在自定义的拦截器中获取request中的数据,想获取到的是JSON字符串 那需要在拦截器中写这样一个方法 public static String getOpenApiRequest ...

  7. Spring Boot配置拦截器及实现跨域访问

    拦截器功能强大,能够深入方法前后,常应用于日志记录.权限检查和性能检测等,几乎是项目中不可或缺的一部分,本文就来实现Spring Boot自定义拦截器的配置. 理论指导 问:Spring Boot怎么 ...

  8. spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对照与注意事项

    原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.o ...

  9. Spring实现自定义注解并且配置拦截器进行拦截

    有时候我们会自定义注解,并且需要配置拦截器对请求方法含有该自定义注解的方法进行拦截操作 自定义注解类 NeedToken.java import java.lang.annotation.Docume ...

随机推荐

  1. 【POJ1426】Find The Multiple

    本题传送门 本题知识点:深度优先搜索 | 宽度优先搜索 题意很简单,让我们找一个只有1和0组成的十位数是n的倍数的数. 这题一开始吓到我了--因为Output里说输出的长度最长不超过100位???那是 ...

  2. Java finally未被执行的情况

    一种是先执行了用于终止程序的System.exit()方法,或进程被关闭 还有一种情况是,当前线程一直在执行,在一些业务逻辑里面跳不出来,看上去就像finally一直未被执行 线程被终止的时候也会执行 ...

  3. [python]pypy优化python性能

    下载地址:https://pypy.org/download.html # python2.7版本 yum install pypy # python3.6版本https://bitbucket.or ...

  4. 常见 SQL 语句的加锁分析

    参考: https://www.aneasystone.com/archives/2017/12/solving-dead-locks-three.html

  5. 分布式快照算法: Chandy-Lamport 算法

    转载https://zhuanlan.zhihu.com/p/53482103 这哥们写的好,顺便转过来吧,当做学习用. 分布式快照算法: Chandy-Lamport 算法 0. 引言 Spark ...

  6. docker部署spring boot项目在服务器上

    IDE:idea 工具:docker spring boot:2.0.1 ======================================== 简单记录一下流程,以供参考: 第一步:首先得 ...

  7. [转]import xxx from 和 import {xxx} from的区别

    原文地址:https://www.cnblogs.com/Abner5/p/7256043.html 1.vue import FunName from ‘../xxx’ 1.js export de ...

  8. [ ceph ] CEPH 部署完整版(CentOS 7 + luminous)

    1. 前言 拜读了 胖哥的(el7+jewel)完整部署 受益匪浅,目前 CEPH 已经更新到 M 版本,配置方面或多或少都有了变动,本博文就做一个 ceph luminous 版本完整的配置安装. ...

  9. Spring Boot JDBC:加载DataSource过程的源码分析及yml中DataSource的配置

    装载至:https://www.cnblogs.com/storml/p/8611388.html Spring Boot实现了自动加载DataSource及相关配置.当然,使用时加上@EnableA ...

  10. 问题解决: 此文件来自其他计算机,可能被阻止以帮助保护该计算机/WORD在试图打开文件时遇到错误……

    最近,在打开下载的office文档(包括word.excel.ppt等)时候,总是无法直接打开,错误提示如下: 无论是邮件中的还是别的网站下载的,均提示该错误.后来搜索相关资料发现,修改其文件属性即可 ...