手把手教你在Java后端如何有效地添加拦截器

   在安全编码规范中,在Java后端controller层接口需要对调用者的身份进行确认,以防非法用户进行访问。若是在controller层的每个接口处都添加逻辑判断,那么代码重复度高,并且费力费时。此时,就需要在请求到达controller层时提前截取数据流,对相关数据进行校验。在这里将要提到的方式就是在后端添加http拦截器,这样每一次的http请求都需要经过拦截器的认证后才可以继续往下走。那么如何有效地添加拦截器呢?下面将会详细给告诉你怎么添加。

  (1)为了方便代码管理,我们先创建一个文件夹,其名为interceptor,与controller文件夹处于同一级,如下图所示:

  

  (2)在interceptor文件夹中创建一个拦截器配置文件,其名称为InterceptorConfig.java,内容如下:

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;



猜你喜欢

转载自www.cnblogs.com/bien94/p/12087851.html