💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
拦截器可以拦截请求也可以拦截响应。使用拦截器的步骤如下: <br/> **1. 实现接口HandlerInterceptor** ```java public class CustomHandlerInterceptor implements HandlerInterceptor { /** * 在请求到达目标方法之前该方法首先被执行 * * @param request * @param response * @param handler * @return 返回true则允许通过,false则拦截 * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle:" + request.getRequestURI()); return true; } /** * 在后端响应数据到前端之前该方法被调用 * * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } /** * 响应完成之后该方法被调用,可以在这个方法中做一些释放资源的工作 * * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); } } ``` **2. 注册拦截器并设置拦截规则** *`resources/springmvc-servlet.xml`* ```xml <mvc:interceptors> <mvc:interceptor> <!-- 所有以 /sys/,或 /syo/ 为前缀的请求都会被拦截器拦截,其他的不会被拦截 --> <mvc:mapping path="/sys/**" /> <mvc:mapping path="/syo/**" /> <bean class="com.learn.springmvc02.interceptor.CustomHandlerInterceptor" /> </mvc:interceptor> </mvc:interceptors> ``` **3. controller层** ```java @Controller public class AccountController { @RequestMapping("/sys/account") public String toAccount() { return "account"; } @ResponseBody @PostMapping("/syo/account") public Account getAccount(Account account) { System.out.println(account); return account; } } ``` **4. 测试** 访问 http://localhost:8080/mvc/sys/account 、http://localhost:8080/mvc/syo/account 这些以`/sys/`、`syo`为前缀的请求将会被拦截。 ``` //拦截器中将会打印如下信息 preHandle:/mvc/syo/account postHandle afterCompletion preHandle:/mvc/sys/account postHandle afterCompletion ```