【Spring】数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误

本文主要是介绍【Spring】数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误

实习时导师让写一个平台信息导出为Excel的功能,写完之后发现文件正常导出,但控制台一直报Stream is closed错误。在网上找了大半天,都说是使用 OutputStream时关闭了流导致的,这也确实是可能导致报错的原因之一,但我并未手动关闭OutputStream,排查半天,问了旁边大佬才知道文件下载接口不能有返回值。。。。。。。。。。因为接口被调用后response会自动关闭ServletOutputStream,而return时会再次自动关闭OutputStream,就会导致 Stream is closed问题。

以下为问题记录(读者可忽略)

导出文件正常:

image-20230915155529371

报错信息:

image-20230915155316789

java.io.IOException: UT010029: Stream is closedat io.undertow.servlet.spec.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:138)at com.fasterxml.jackson.core.json.UTF8JsonGenerator._flushBuffer(UTF8JsonGenerator.java:2171)at com.fasterxml.jackson.core.json.UTF8JsonGenerator.flush(UTF8JsonGenerator.java:1184)at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1009)at org.springblade.core.tool.jackson.AbstractReadWriteJackson2HttpMessageConverter.writeInternal(AbstractReadWriteJackson2HttpMessageConverter.java:116)at org.springblade.core.tool.jackson.MappingApiJackson2HttpMessageConverter.writeInternal(MappingApiJackson2HttpMessageConverter.java:73)at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290)at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:183)at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135)at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)at javax.servlet.http.HttpServlet.service(HttpServlet.java:497)at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)at javax.servlet.http.HttpServlet.service(HttpServlet.java:584)at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)at org.springblade.core.log.filter.LogTraceFilter.doFilter(LogTraceFilter.java:39)at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)at org.springblade.core.boot.request.BladeRequestFilter.doFilter(BladeRequestFilter.java:58)at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:114)at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)at io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:117)at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)at io.undertow.servlet.handlers.SendErrorPageHandler.handleRequest(SendErrorPageHandler.java:52)at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:275)at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:79)at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:134)at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:131)at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:255)at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:79)at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:100)at io.undertow.server.Connectors.executeRootHandler(Connectors.java:387)at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:852)at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2019)at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1558)at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1423)at org.xnio.XnioWorker$WorkerThreadFactory$1$1.run(XnioWorker.java:1282)at java.lang.Thread.run(Thread.java:750)

报错接口如下:

	@GetMapping("/exportExcel")@ApiOperationSupport(order = 10)@ApiOperation(value = "导出数据为Excel表格", notes = "导出数据为Excel表格")public R exportExcel(@ApiParam(value = "表单id", required = true) @RequestParam Long formId,@ApiParam(value = "数据列表ids", required = true) @RequestParam String ids,HttpServletResponse response) {List<Map<String, Object>> data;List<Long> longIds = Func.toLongList(ids);//通过表单id,获取表单配置FormEntity formEntity = formService.getById(formId);if (null == formEntity) {return R.fail("未查询到表单");
//			throw new ServiceException("未查询到表单");}// 标题字段nameSet<String> title;// 导出的字段列表List<FormFieldDTO> formLabels;try {Long modelId = formEntity.getModelId();ModelBase model = modelBaseService.getById(modelId);String tableName = model.getName();Integer type = model.getType();// 获取当前表单的字段信息List<FormFieldDTO> formFields = formService.getFormFieldsInfoByFormId(formId);Set<String> fieldSet = formFields.stream().filter(item -> item.getModelFieldId() != null).map(FormFieldDTO::getName).collect(Collectors.toSet());// 更换数据源Long dataSourceId = model.getSourceId();if (dataSourceId != null) {DynamicDataSourceContextHolder.push(dataSourceId.toString());}// 获取当前表单的所有字段List<Map<String, Object>> fieldsList = baseSqlService.getAllFields(tableName, type);Set<String> allFields = fieldsList.get(0).keySet();// 求公共字段fieldSet.retainAll(allFields);// 获取公共字段对应的nameformLabels = formFields.stream().filter(item -> fieldSet.contains(item.getName())).collect(Collectors.toList());// 判断数据库表中是否存在status字段if (allFields.contains("status")){fieldSet.add("status");}// 提取字段名// 通过IFNULL函数解决mybatis映射Map时忽略控制字段问题title = fieldSet;String fields = String.join(",", fieldSet);data = baseSqlService.queryFieldsByIds(tableName, fields, longIds);} catch (Exception e) {return R.fail(e.toString());
//			e.printStackTrace();
//			return;} finally {// 将数据源切换回来DynamicDataSourceContextHolder.clear();}// 结果数据匹配中文信息List<Map<String, Object>> recordsWrapper = BaseListRecordsWrapper.build().wrapper(data, formEntity.getStyleJson());// 获取表单列表中不存在的字段名// **此处需要创建新的HashSet对象,否则removeAll会删除原信息值**Set<String> recordFields = new HashSet<>(recordsWrapper.get(0).keySet());recordFields.removeAll(title);recordFields.forEach(item -> {FormFieldDTO formFieldDTO = new FormFieldDTO();formFieldDTO.setName(item);if ("statusName".equals(item)) {formFieldDTO.setLabel("状态");} else if ("create_user_name".equals(item)){formFieldDTO.setLabel("创建人");} else {formFieldDTO.setLabel(item);}formLabels.add(formFieldDTO);});// 剔除原有的status,仅导出statusName即可if (recordFields.contains("statusName")){recordsWrapper.forEach(item -> item.remove("status"));title.remove("status");}if (recordFields.contains("create_user_name")){recordsWrapper.forEach(item -> item.remove("create_user"));title.remove("create_user");}// 将多出的字段添加至标题(如statusName)title.addAll(recordFields);Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");try {ExportUtil.writeExcel(response, recordsWrapper, dateFormat.format(date), "默认页", title, formLabels);} catch (IOException e) {log.error(e.toString());}return R.success("下载成功!");}
}

修改后:

	@GetMapping("/exportExcel")@ApiOperationSupport(order = 10)@ApiOperation(value = "导出数据为Excel表格", notes = "导出数据为Excel表格")public void exportExcel(@ApiParam(value = "表单id", required = true) @RequestParam Long formId,@ApiParam(value = "数据列表ids", required = true) @RequestParam String ids,HttpServletResponse response) {List<Map<String, Object>> data;List<Long> longIds = Func.toLongList(ids);//通过表单id,获取表单配置FormEntity formEntity = formService.getById(formId);if (null == formEntity) {throw new ServiceException("未查询到表单");}// 标题字段nameSet<String> title;// 导出的字段列表List<FormFieldDTO> formLabels;try {Long modelId = formEntity.getModelId();ModelBase model = modelBaseService.getById(modelId);String tableName = model.getName();Integer type = model.getType();// 获取当前表单的字段信息List<FormFieldDTO> formFields = formService.getFormFieldsInfoByFormId(formId);Set<String> fieldSet = formFields.stream().filter(item -> item.getModelFieldId() != null).map(FormFieldDTO::getName).collect(Collectors.toSet());// 更换数据源Long dataSourceId = model.getSourceId();if (dataSourceId != null) {DynamicDataSourceContextHolder.push(dataSourceId.toString());}// 获取当前表单的所有字段List<Map<String, Object>> fieldsList = baseSqlService.getAllFields(tableName, type);Set<String> allFields = fieldsList.get(0).keySet();// 求公共字段fieldSet.retainAll(allFields);// 获取公共字段对应的nameformLabels = formFields.stream().filter(item -> fieldSet.contains(item.getName())).collect(Collectors.toList());// 判断数据库表中是否存在status字段if (allFields.contains("status")){fieldSet.add("status");}// 提取字段名// 通过IFNULL函数解决mybatis映射Map时忽略控制字段问题title = fieldSet;String fields = String.join(",", fieldSet);data = baseSqlService.queryFieldsByIds(tableName, fields, longIds);} catch (Exception e) {e.printStackTrace();return;} finally {// 将数据源切换回来DynamicDataSourceContextHolder.clear();}// 结果数据匹配中文信息List<Map<String, Object>> recordsWrapper = BaseListRecordsWrapper.build().wrapper(data, formEntity.getStyleJson());// 获取表单列表中不存在的字段名// **此处需要创建新的HashSet对象,否则removeAll会删除原信息值**Set<String> recordFields = new HashSet<>(recordsWrapper.get(0).keySet());recordFields.removeAll(title);recordFields.forEach(item -> {FormFieldDTO formFieldDTO = new FormFieldDTO();formFieldDTO.setName(item);if ("statusName".equals(item)) {formFieldDTO.setLabel("状态");} else if ("create_user_name".equals(item)){formFieldDTO.setLabel("创建人");} else {formFieldDTO.setLabel(item);}formLabels.add(formFieldDTO);});// 剔除原有的status,仅导出statusName即可if (recordFields.contains("statusName")){recordsWrapper.forEach(item -> item.remove("status"));title.remove("status");}if (recordFields.contains("create_user_name")){recordsWrapper.forEach(item -> item.remove("create_user"));title.remove("create_user");}// 将多出的字段添加至标题(如statusName)title.addAll(recordFields);Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");try {ExportUtil.writeExcel(response, recordsWrapper, dateFormat.format(date), "默认页", title, formLabels);} catch (IOException e) {log.error(e.toString());}}

再次调用接口已无报错:

image-20230915155607055

这篇关于【Spring】数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/742380

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

关于数据埋点,你需要了解这些基本知识

产品汪每天都在和数据打交道,你知道数据来自哪里吗? 移动app端内的用户行为数据大多来自埋点,了解一些埋点知识,能和数据分析师、技术侃大山,参与到前期的数据采集,更重要是让最终的埋点数据能为我所用,否则可怜巴巴等上几个月是常有的事。   埋点类型 根据埋点方式,可以区分为: 手动埋点半自动埋点全自动埋点 秉承“任何事物都有两面性”的道理:自动程度高的,能解决通用统计,便于统一化管理,但个性化定