1.设置日志级别:
设不设都无所谓
2.Springboot整合springmvc拦截器
2.1自定义拦截器(实现HandlerInterceptor接口就行),忘了就看以前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定义配置类(得实现WebMvcConfigurer和记得添加@Configuration表名为配置类),addPathPatterns里面可以设置要拦截的请求路径的:
其他的可参考:配置的请求路径写法
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("/*/**");
}
}
总的代码:
测试:启动启动器类,
在浏览器输入http://localhost:81/hello1 (因为我的拦截器的配置类是所以都拦截的,所以这个请求会被拦截):
test成功