企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
在调用控制器之前或之后会调用拦截器 1.preHandle 在调用控制器之前 2.postHandle 在调用控制器之后 3.afterCompletion 在视图渲染结束后 **1.自定义拦截器** ~~~ package com.nobb.controller.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //自定义的拦截器,需要继承 HandlerInterceptor public class MyInterceptor implements HandlerInterceptor { @Override //执行Controller方法之前调用 // 可以通过返回值,选择是否阻止Controller方法调用 // true:不阻止 false:阻止 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("public boolean preHandle!"); return true; } @Override //执行Controller方法之后调用 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("public void postHandle!"); } @Override //视图渲染结束后调用 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("public void afterCompletion"); } } ~~~ **2.spring-mvc.xml 配置拦截器** ~~~ <!--指定包及子包的文件,交给了spring管理--> <context:component-scan base-package="com.nobb.controller"/> <!--启用注解配置SpringMVC--> <mvc:annotation-driven/> <mvc:interceptors> <mvc:interceptor> <!--拦截hello下的所有路径--> <mvc:mapping path="/hello/**"/> <bean class="com.nobb.controller.interceptor.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors> ~~~