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

posted @ 2019-11-20 09:13  张瑞丰  阅读(1413)  评论(0编辑  收藏  举报