SpringMvc——拦截器学习
1、拦截器(Interceptor)是一种动态拦截方法调用的机制
作用:
在指定的方法调用前后执行预先设定后的的代码
阻止原始方法的执行
2、拦截器与过滤器区别
归属不同:Filter属于Servlet技术,Interceptor.属于SpringMVC技术
拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强
在SpringMvc中进行拦截器配置,一般写在controller下,拦截器为业务层服务。
package com.itheima.controller.Interceptor; 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 ProjectInterceptor implements HandlerInterceptor { //原始程序运行之前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandler...."); //false代表终止原始操作 return true; } //运行之后 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandler..."); } //运行之后 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion..."); } }
在springMvc中加载拦截器
package com.itheima.config; import com.itheima.controller.Interceptor.ProjectInterceptor; 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 SpringWebSupport extends WebMvcConfigurationSupport { @Autowired private ProjectInterceptor projectInterceptor; @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/pages/**").addResourceLocations("/pages/"); } // 拦截器 //设置拦截器对象和拦截请求 @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(projectInterceptor).addPathPatterns("/books"); //配置拦截路径 } }
加载完之后,需要在SpringMvc配置文件中进行扫描。
拦截器的执行流程