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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM