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());
        }
    }
  • 相关阅读:
    贪吃蛇 666
    安装postgresql
    linux CentOS6.5 yum安装mysql 5.6
    centos--git搭建之Gogs安装
    查看mysql 默认端口号和修改端口号
    centos之mysql安装配置使用
    流媒体服务器SRS部署
    vue用webpack打包时引入es2015插件
    log4j2的log输出到tomcat/logs目录下及使用(转)
    log4j2的配置文件log4j2.xml笔记
  • 原文地址:https://www.cnblogs.com/chichung/p/12118686.html
Copyright © 2011-2022 走看看