自定义拦截器步骤
1 创建拦截器类实现HandlerInterceptor
@Controller public class TargetController { @RequestMapping("/target") public ModelAndView show() { System.out.println("目标资源执行"); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("name","zl"); modelAndView.setViewName("index"); return modelAndView; } }
public class MyInterceptor1 implements HandlerInterceptor{ //在目标方法执行之前执行 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle"); String param = request.getParameter("param"); if("yes".equals(param)) { return true; } else { request.getRequestDispatcher("/error.jsp").forward(request, response);; return false;//返回true代表放行 } } //在目标方法执行之后,视图对象返回之前执行 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub modelAndView.addObject("name", "zhangsan"); System.out.println("postHandle"); } //在流程都执行完毕后执行 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub System.out.println("afterCompletion"); } }
2 配置拦截器
<!-- 配置拦截器 --> <mvc:interceptors> <mvc:interceptor> <!-- 对哪些资源执行拦截操作 --> <mvc:mapping path="/**"/> <bean class="com.zl.interceptor.MyInterceptor1"></bean> </mvc:interceptor> <mvc:interceptor> <!-- 对哪些资源执行拦截操作 --> <mvc:mapping path="/**"/> <bean class="com.zl.interceptor.MyInterceptor2"></bean> </mvc:interceptor> </mvc:interceptors>
3 测试拦截器的拦截效果
标签:拦截器,Spring,request,System,ModelAndView,modelAndView,public From: https://www.cnblogs.com/zlyyds/p/16933040.html