• SpringBoot-拦截器配置


    SpringBoot-拦截器配置

    SpringBoot-拦截器配置

    在我们的SSM项目中,可以在web.xml中配置拦截器,但是在SpringBoot中只能使用java类来配置,配置方法如下。

    创建拦截器

    1. 首先创建一个类如MyInterceptor
    2. 实现HandlerInterceptor接口
    3. 重写其方法
    package cn.ryafoo.core.interceptor;
    
    import lombok.Builder;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.lang.Nullable;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    /**
     * @author 张瑞丰
     * @description
     * @date 2019/11/19
     */
    @Slf4j
    public class MyInterepter implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.info("into my api");
            return  true;
        }
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        }
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        }
    }
    
    

    加载拦截器

    1. 创建一个新类,如WebMvcConfig
    2. 实现WebMvcConfigurer
    3. 在其类上加入@Configuration注解
    4. 重写addInterceptors方法
    5. 在方法内加入拦截规则,如registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    package cn.ryafoo.core.config;
    
    import cn.ryafoo.core.interceptor.MyInterepter;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    /**
     * @author 张瑞丰
     * @description
     * @date 2019/11/19
     */
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MyInterepter()).addPathPatterns("/**");
        }
    }
    
    
  • 相关阅读:
    Sqlserver 批量数据更改
    mysql not in、left join、IS NULL、NOT EXISTS 效率问题记录
    SQLServer 与 MySQL
    MySQL 行号(类似SQLServer的row_number())
    c# 字符串排序 (面试题)
    c# 多线程里面创建byte数组发生内存溢出异常求解
    c# 遇到的问题,求解?
    solr-4.10.3.tgz.tgz下载
    VMware虚拟机克隆或复制linux后无法上网的解决方案
    通配符的匹配很全面, 但无法找到元素 'dubbo:application' 的声明。
  • 原文地址:https://www.cnblogs.com/zhangruifeng/p/11895573.html
Copyright © 2020-2023  润新知