一、背景
拦截请求,查看商品是否存在
二、代码
@Component
public class AccessInterceptor implements HandlerInterceptor {
private final Logger logger = LoggerFactory.getLogger(AccessInterceptor.class);
@Resource
private AccessService accessService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
requestURI = requestURI.substring(requestURI.length()-6);
logger.info("请求:{}", requestURI);
Shop shop = accessService.getOne(requestURI);
if (shop != null) {
return true;
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
try (OutputStream out = response.getOutputStream()) {
out.write(JSONUtil.toJsonStr(resultData).getBytes(StandardCharsets.UTF_8));
out.flush();
} catch (IOException e) {
log.error("商品不存在", e);
}
return false;
}
}
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Resource
private AccessInterceptor accessInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 资源访问拦截器
registry.addInterceptor(resourceAccessInterceptor)
.addPathPatterns("/**/manage/shop/**");
}
}
三、总结
使用filter也可以做到
Interceptor和Filter区别:
- Filter依赖于Servlet容器,Interceptor基于SpringMVC。所以Filter只能在请求时使用,而Interceptor可以作用每个方法
- Filter几乎对所有的请求起作用,而Interceptor对mapping请求起作用
- Filter是基于函数回调的,而Interceptor则是基于反射实现的代理类
- Interceptor可以被多次调用,而Filter只能在Servlet容器初始化时调用一次
- Interceptor可以注入IOC容器中的依赖,而Filter不能,可以参考我前面Filter使用
二者对比不仅仅以上5条。一般在Spring、SpringBoot项目推荐使用Interceptor
|