springmvc的Interceptor拦截器和servlet的filter过滤器
1、springmvc的Interceptor拦截器和servlet的filter过滤器springboot实现方式
package com.liubaihui.lianxi01.controller; import org.springframework.stereotype.Component; import javax.servlet.*; import java.io.IOException; @Component public class MyFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("过滤器dofilter被执行了"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("过滤器初始化方法执行了"); } }
package com.liubaihui.lianxi01.controller; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyInterceptor 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被执行了"); HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion被执行了"); HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
package com.liubaihui.lianxi01.controller; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Component public class MyMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) .addPathPatterns("/**"); } }
2、springmvc的Interceptor拦截器和servlet的filter过滤器区别
1、filter是servlet提供的、interceptor是springmvc提供的接口
2、filter是基于回调执行的,interceptor是动态代理方式实现的
3、filter可以做一下初始化方法init()处理
4、interceptor可以处理controller方法执行前中后执行做处理,filter只能做请求一次拦截请求
3、springmvc的Interceptor拦截器和servlet的filter过滤器和aop执行顺序
过滤器----拦截器---aop
参考:过滤器实现3种方式:https://blog.csdn.net/shaoming314/article/details/121366966
标签:拦截器,springmvc,filter,过滤器,import,servlet,public From: https://www.cnblogs.com/liubaihui/p/17111189.html