springboot拦截器和过滤器

过滤器

Filter依赖于servlet容器,属于servlet规范的一部分
Filter的生命周期由servlet容器管理
Filter可拦截所有web资源(包括jsp,Servlet,静态资源,Controller)

自定义Filter

import javax.servlet.*;
@WebFilter(urlPatterns = "/dataSharingStatic/offline/orderPdfFile/*")
public class MyFilter implements Filter {
    Log log = LogFactory.getLog(MyFilter.class);
    @Resource
    private IApplyOrderProcessDetailMapper applyOrderProcessDetailMapper;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String requestURI = request.getRequestURI();
        String[] split = requestURI.split("/");
        if (split.length == 6) {
            String orderId = split[split.length-2];

            String fileName = split[split.length-1];
            String decode = URLDecoder.decode(fileName, StandardCharsets.UTF_8.toString());

            File file = new File("/data/static/dataSharingStatic/offline/orderPdfFile/" + orderId + "/" + decode);
            if (file.exists()) {
                //文件存在再判断
                List<ApplyOrderProcessDetail> applyOrderDetailByOrderIdAndFileurl = applyOrderProcessDetailMapper.findApplyOrderDetailByOrderIdAndFileurl(orderId, fileName);
                if (applyOrderDetailByOrderIdAndFileurl != null && applyOrderDetailByOrderIdAndFileurl.size() > 0) {
                    Integer appendixFileDownloadCount = applyOrderDetailByOrderIdAndFileurl.get(0).getAppendixFileDownloadCount();
                    appendixFileDownloadCount = appendixFileDownloadCount == null ? 0 : appendixFileDownloadCount;
                    Integer newDownloadCount = appendixFileDownloadCount + 1;

                    if (appendixFileDownloadCount == null || appendixFileDownloadCount < 3) {
                        //<3更新数据库
                        if(newDownloadCount<3)
                            applyOrderProcessDetailMapper.updateApplyOrderCount(orderId, fileName, newDownloadCount);
                    }else {
                        //等于3时更新数据库并删除源文件
                        file.delete();
                        //更新url null
                        applyOrderProcessDetailMapper.updateApplyOrderCountAndUrl(orderId, fileName, newDownloadCount, null);
                    }
                }
            }else {
                log.info("文件不存在 "+URLDecoder.decode(requestURI, StandardCharsets.UTF_8.toString()));
            }
        }
        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

启动类上添加servlet组件扫描

//任意Controller执行时都会被自定义过滤器MyFilter拦截
@ServletComponentScan(basePackages = "com.meteorological.filtertest")
public class SpringbootApplication {
	public static void main(String[] args){
		SpringApplication.run(SpringbootApplication.class, args);
	}
}

拦截器

Interceptor依赖于SpringMVC框架
Interceptor通过IOC容器来管理,可通过注入等方式来获取其Bean的实例
Interceptor则只拦截Controller

自定义拦截器

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //ip地址
        String remoteAddr = request.getRemoteAddr();

        HttpSession session = request.getSession();
        Integer count = (Integer)session.getAttribute("count");
        count = Objects.isNull(count)?1:++count;
        session.setAttribute("count",count);
        System.out.println("MyInterceptor "+ remoteAddr + " "+ count);
        //放行
        return true;
    }
}

将自定义拦截器添加到ioc容器中

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //将自定义拦截器添加到ioc容器中
        //任意Controller执行时都会被自定义拦截器MyInterceptor拦截
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值