SpringMVC:拦截器

一般我们会做一些统一的操作这个时候我们需要使用springmvc提供的拦截器,例如token的验证,字段必填的操作,接口超时判断,签名验证,字段加密等操作,所以我们需要了解执行先后顺序。 我们来简单介绍下实现过程及对应代码,执行结果:

1、定义自己的spring mvc拦截器需要实现HandlerInterceptor 接口或者继承HandlerInterceptorAdapter

2、boolean preHandle()方法在controller被调用之前调用;

3、void postHandle()方法在controller被调用之后调用,可在modelandview中加入数据,比如当前时间;

4、void afterCompletion()在呈现视图之后调用,可用于清理资源等;

5、当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法

public class MyInterceptor1 extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("-------preHandle1-------");
        // 如果返回false,则不再调用之后的方法  
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		System.out.println("-------postHandle1-------");
		if (modelAndView != null) { 
            // 当前时间  
			modelAndView.addObject("now", new Date());
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		System.out.println("-------afterCompletion1-------");
	}


}
 public class MyInterceptor2 extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("-------preHandle2-------");
        // 如果返回false,则不再调用之后的方法  
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		System.out.println("-------postHandle2-------");
		if (modelAndView != null) { 
            // 加入当前时间  
			modelAndView.addObject("now", new Date());
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		System.out.println("-------afterCompletion2-------");
	}


}

	
		
		
	
	
		
		
	
  

会根据配置先后顺序往下执行,执行结果如下图 >> 

SpringMVC:拦截器_第1张图片

你可能感兴趣的:(SpringCloud,spring,boot)