1. Set the log level:
It doesn't matter whether you set it or not
2. Springboot integrates springmvc interceptor
2.1 Custom interceptor (implement HandlerInterceptor interface is fine), if you forget, just look at the previous springmvc:
package com.itheima.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author QLBF
* @version 1.0
* @date 2021/2/21 20:54
*/
@Slf4j
public class MyInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
log.debug("这是MyInterceptor拦截器的preHandle方法");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
log.debug("这是MyInterceptor拦截器的postHandle方法");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
log.debug("这是MyInterceptor拦截器的afterCompletion方法");
}
}
2.2 Define the configuration class (you must implement WebMvcConfigurer and remember to add the @Configuration table name to the configuration class ), the request path to be intercepted can be set in addPathPatterns :
Other references: How to write the configured request path
package com.itheima.config;
import com.itheima.interceptor.MyInterceptor;
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;
/**
* @author QLBF
* @version 1.0
* @date 2021/2/21 20:58
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer{
/**
* * 将拦截器注册到spring ioc容器
* * @return myInterceptor(是自己创建的拦截器类)
* */
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}
/***
* 重写该方法;往拦截器链添加自定义拦截器
* * @param registry 拦截器链
* */
@Override
public void addInterceptors(InterceptorRegistry registry) {
//通过registry添加myInterceptor拦截器,并设置拦截器路径为 /*'
//addPathPatterns("/*") 代表可以拦截所有请求
registry.addInterceptor(myInterceptor()).addPathPatterns("/*/**");
}
}
The total code:
test: start the launcher class,
enter http://localhost:81/hello1 in the browser (because my interceptor configuration class is all intercepted, so this request will be intercepted):
test success