springboot 是spring框架的二次升华,简化了配置,提高了开发效率。拦截器是spring 提供的基于AOP思想的实现。过滤器filter是servlet的API,比较依赖servlet,他们有不同也有一些相似的地方。1Filter基于servlet ,主要用于servlet存在的环境。拦截器用于servlet,也可以用于其他环境中。2Filter是servlet规范来提供支持,拦截器是spring框架来提供支持。3Filter的使用主要在servlet的前后,拦截器可以深入到每个角落。时使用拦截器?何时使用过滤器?1如果是非spring项目,那么不能拦截器,只能用过滤器。2 如果是处理controller前后,既可以使用拦截器也可以使用过滤器。下面是springboot里面实现filter的例子

// 注入spring容器

@Component
// 定义filterName 和过滤的url
@WebFilter(filterName = "my2Filter" ,urlPatterns = "/*")
public class My2Filter implements Filter {@Override
br/>@Override

}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("filter2");}@Overridepublic void destroy() {}

}

接下来实现一个springboot里面的拦截器的例子。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

@Overridepublic void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new GlobalInterceptor()).addPathPatterns("/**");}

}

import cn.vcinema.tool.security.session.SessionValidateResultEnum;
import cn.vcinema.tool.security.session.UserSessionInfo;
import cn.vcinema.tool.security.session.UserSessionUtils;
import com.pumpkin.conf.MallConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GlobalInterceptor implements HandlerInterceptor {

private final static Logger LOGGER = LoggerFactory.getLogger(GlobalInterceptor.class);@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String userId = request.getHeader("user_id"); String sessionId = request.getHeader("session_id"); String deviceId = request.getHeader("device_id"); LOGGER.info("headers:user_id=" + userId + ",session_id=" + sessionId + ",device_id=" + deviceId); UserSessionInfo info = new UserSessionInfo(userId, sessionId, deviceId); SessionValidateResultEnum resultEnum = UserSessionUtils.validateSession(MallConfig.getRunMode(), info); return true;}

}