创建一个Interceptor类实现HandlerInterceptor接口,重写preHandle(),postHandle(),afterCompletion() 三个方法
如下代码,我们就创建了一个Spring的拦截器
/**
* @author rick
*/
@Component
public class EasyLogControllerInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 在controller调用之前执行
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info(request.getRequestURI()+"preHandle开始执行");
return true;
}
/**
* 在controller调用中执行
*/
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
logger.info(request.getRequestURI()+"postHandle开始执行");
}
/**
* 在controller调用后执行
*/
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
logger.info(request.getRequestURI()+"afterCompletion执行结束");
}
}
创建拦截器之后,我们还需要将其注册到Spring程序中,以便启用它。
注册拦截器
创建一个Spring配置类实现WebMvcConfigurer接口,并重写addInterceptors()方法,用于将拦截器添加到程序中
作用是控制拦截哪个controller,拦截哪个路径,放开哪个路径
/**
* @author rick
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private EasyLogControllerInterceptor easyLogControllerInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//addPathPatterns用于添加拦截路径
//excludePathPatterns用于添加不拦截的路径
registry.addInterceptor(easyLogControllerInterceptor)
.addPathPatterns("/send")
.addPathPatterns("/hello");
}
/**
* 此方法用于配置静态资源路径
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/my/");
}
}
/**
* @author rick
*/
@RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@GetMapping("/hello")
public Map<String,String> hello(){
Map<String,String> response=new HashMap<>();
logger.info("------hello");
response.put("msg","hello");
return response;
}
@GetMapping("/send")
public Map<String,String> send(){
Map<String,String> response=new HashMap<>();
logger.info("------send");
response.put("msg","send");
return response;
}
}