getWriter() has already been called for this response异常

  • Post author:
  • Post category:其他


文章摘要

java.lang.IllegalStateException: getWriter() has already been called for this response异常(100%解决)

首先看下抛的异常详情:


java.lang.IllegalStateException: getWriter() has already been called for this response


at org.apache.catalina.connector.Response.getOutputStream(Response.java:585)

at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:194)

at javax.servlet.ServletResponseWrapper.getOutputStream(ServletResponseWrapper.java:100)


at org.springframework.http.server.ServletServerHttpResponse.getBody(ServletServerHttpResponse.java:89)

at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:244)

at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:106)

at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:231)

at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:203)

at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)

at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:113)

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)

at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)

at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)

at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)

at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)

同常我们利用java导出CSV,txt等不同格式文件,会出现这个异常。

对待这个异常,通常有俩种解决办法,本人提供思路和少量代码展示。

思路:

一:查看getWriter(),outPutStream是否同时存在,这俩个进行文件写入操作只能用一个

二:SpringMvc,springBoot,Servelt中发送Post请求时,会默认取消HttpResponse,正如抛的异常

代码展示(解决办法):

controller层(servlert,springMvc,Servlet原理都一样):

具体导出方法:

异常解决验证:

当我抛了此异常时:用了方案1已解决