Spring Boot拦截器实现步骤及测试实例

第一步,定义拦截器:

package com.zl.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class myInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    System.out.println("preHandle");
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    System.out.println("preHandle");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    System.out.println("preHandle");
  }
}

控制台打印三个输出语句,作为测试。

第二步:配置拦截器

package com.zl.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
  }
  @Bean
  myInterceptor myInterceptor(){
    return new myInterceptor();
  }
}

将定义的拦截器注入到这个配置方法中,并拦截所有路径。

第三步:写个接口测试

package com.zl.interceptor;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class helloController {
  @GetMapping("/hello")
  public String hello(){
    return "hello";
  }
}

测试结果

定义的拦截器三个方法都执行了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持云海天教程。