zoukankan      html  css  js  c++  java
  • springboot项目中的拦截器

    我们在提供 API 的时候,经常需要对 API 进行统一的拦截,比如进行接口的安全性校验。

    创建一个拦截器类:ApiInterceptor,并实现 HandlerInterceptor 接口:

    public class ApiInterceptor implements HandlerInterceptor {
        //请求之前
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            System.out.println("进入拦截器");
            return true;
        }
        //请求时
        @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 {
    
        }
    }

    @SpringBootConfiguration 注解的类继承 WebMvcConfigurationSupport 类,并重写 addInterceptors 方法,将 ApiInterceptor 拦截器类添加进去,代码如下:

    @SpringBootConfiguration
    public class WebConfig extends WebMvcConfigurationSupport{
    
        @Override
        protected void addInterceptors(InterceptorRegistry registry) {
            super.addInterceptors(registry);
            registry.addInterceptor(new ApiInterceptor());
        }
    }
  • 相关阅读:
    PHP
    思科模拟器
    路由器
    服务器
    Windows Server 2008 笔记【瞎写】
    Day1 T3 数列
    java中自定义excel模板并且填充内容
    springMVC接收值list时,超过256出现IndexOutOfBoundsException
    java将日期转换成周几
    两个tomcat配置各自的SSL证书(前后端分离)
  • 原文地址:https://www.cnblogs.com/chichung/p/12118686.html
Copyright © 2011-2022 走看看