1. 创建Interceptor.java
如果实现方法没有提示,手动添加:
Ctrl + o
@Component
public class Interceptor implements HandlerInterceptor {
/*处理请求之前*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("处理请求之前:::::");
return true;
}
/*处理请求之后*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("处理请求之后:::::");
}
/*响应后*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("响应后:::::");
}
}
2. 创建InterceptorConfig.java
@Component
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
Interceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor);
}
}
3. Controller请求
@RequestMapping("/testRequest")
@ResponseBody
public String TestRequest(){
System.out.println("请求中...");
return "ok";
}