拦截器与过滤器
流程图
拦截器vs过滤器
拦截器是SpringMVC的技术
过滤器的Servlet的技术
先过过滤器,过滤器过完成才到DispatcherServlet;
拦截器归属于SpringMVC,只可能拦SpringMVC的东西;
拦截器说白了就是为了增强,可以在请求前进行增强,也可以在请求后进行增强,但是不一定同时在前后都增强。
区别
SpringMVC技术架构图
项目Demo
项目地址
Interceptor
package com.test.filtertest.inter;
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;
/**
* @author zhangzengxiu
* @date 2022/4/22
*/
@Component
public class TestInter1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("TestInter1 preHandle...");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("TestInter1 postHandle...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("TestInter1 afterCompletion...");
}
}
Interceptor拦截器要注册
package com.test.filtertest.config;
import com.test.filtertest.inter.TestInter1;
import com.test.filtertest.inter.TestInter2;
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.WebMvcConfigurer;
/**
* @author zhangzengxiu
* @date 2022/4/22
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private TestInter1 testInter1;
@Autowired
private TestInter2 testInter2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//默认/** 拦截所有请求
registry.addInterceptor(testInter1).addPathPatterns("/**");
registry.addInterceptor(testInter2);
}
}
Filter
package com.test.filtertest.filter;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* @author zhangzengxiu
* @date 2022/4/22
*/
@WebFilter(filterName = "TestFilter1", urlPatterns = "/*")
@Order(2)
public class TestFilter1 implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("TestFilter1 filter before ...");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("TestFilter1 filter after ...");
}
@Override
public void destroy() {
}
}
|