首页  编辑  

SpringBoot拦截器处理Controller的请求

Tags: /Java/   Date Created:

 1 import org.springframework.stereotype.Component;
 2 import org.springframework.web.servlet.HandlerInterceptor;
 3 import org.springframework.web.servlet.ModelAndView;
 4 
 5 import javax.annotation.Nullable;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 @Component
10 public class LogInterceptor implements HandlerInterceptor {
11     @Override
12     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
13         System.out.println(String.format("开始处理: %s, %s, Session ID: %s", request.getRequestURI(), request.getQueryString(), request.getRequestedSessionId()));
14         return true;  // 继续处理,返回 false 表示终止后续的处理
15     }
16 
17     @Override
18     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
19         System.out.println(String.format("完成处理: %s, %s, Code: %d", request.getRequestURI(), request.getQueryString(), response.getStatus()));
20     }
21 
22     @Override
23     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception e) throws Exception {
24         System.out.println(String.format("后事处理: %s, %s, Code: %d", request.getRequestURI(), request.getQueryString(), response.getStatus()));
25     }
26 }