拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行
作用:在指定的方法调用前后执行预先设定的代码,阻止原始方法的执行
归属不同:Filter属于Servlet技术,Interception属于SpringMVC技术
拦截内容不同:Filter对所有访问进行增强,Interception仅针对SpringMVC的访问进行增强。
---perHandle --->return----->controller----->postHandle---->afterCompletion----->
---->false---------------------------跳过这一环了-------------------------->
Interception
package com.yang.controller.Interception; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class ProjectInterception implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle..."); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle..."); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion..."); } }
SpringMvcSupport
package com.yang.config; import com.yang.controller.Interception.ProjectInterception; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class SpringMvcSupport extends WebMvcConfigurationSupport { @Autowired private ProjectInterception projectInterception; @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/pages/**").addResourceLocations("/pages/"); } @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(projectInterception).addPathPatterns("/books"); } }
package com.yang.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @ComponentScan({"com.yang.controller","com.yang.config"}) @EnableWebMvc//开启接受json public class SpringMvcConfig { }
拦截器链的运行顺序
true
perHandle:与配置顺序相同,必定运行
postHandle:与配置顺序相反,可能不运行
afterCompletion:与配置顺序相反,可能不运行
false
perHandle:终止了
postHandle; 终止
afterCompletion:到哪一个perHandle终止,则执行它前面的afterCompletion。