获取exception-java.lang.IllegalStateException:已为此响应调用了getOutputStream()

我是jsp的新手,当我尝试通过一些名为cId和passWord的参数调用jsp页面时,我收到此错误,我一直在尝试的代码如下,我已经经历了同样的错误,谷歌搜索,但我仍然得到同样的问题。 代码是:

 <% String cidMessage = "cID"; String passEncrypted = "passWord"; System.out.println("CID ISSSSSSSSSSSS"+cId); if ((cId.equals(cidMessage)) && (passWord.equals(passEncrypted))) { System.out.println("Validation Correct"+cId); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String time = sdf.format(date.getTime()); String xmlOutput = "" + "" + time + "" + "" + "SUCESS" + "" + "" + currentTimeMillis() + "" + "" + "1" + "" + ""; try { byte[] contents = xmlOutput.getBytes(); response.setContentType("text/xml"); response.setContentLength(contents.length); response.getOutputStream().write(contents); response.getOutputStream().flush(); } catch (Exception e) { throw new ServletException(e); } } else { System.out.println("Validation Wrong"+cId); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String time = sdf.format(date.getTime()); String xmlOutput = "" + "" + time + "" + "ERROR" + "" + "ErrorCode" + "" + "" + "ErrorMessage" + "" + ""; try { byte[] contents = xmlOutput.getBytes(); response.setContentType("text/xml"); response.setContentLength(contents.length); response.getOutputStream().write(contents); response.getOutputStream().flush(); } catch (Exception e) { throw new ServletException(e); } } %>  

您不应该尝试在JSP中执行此操作。 JSP已经获得了输出流来写入它的输出。 您需要使用servlet来返回XML。

当您调用response.getOutputStream时,它与JSP(将被编译为servlet)已经获得输出流的事实相冲突。 这就是导致IllegalStateException的原因。

  • 如果你查看getOutputStream()方法的文档:它提到了

抛出IllegalStateException – 如果已在此响应上调用getWriter方法。

  • 这意味着您可以调用getWriter()getOutputStream()方法。

  • 现在在JSP中( 最终在编译的servlet中 ),有一个被定义的隐式变量。 这只是PrintWriter类的一个实例。 这意味着在响应对象上, getWriter()已经被调用,因此在调用getOutputStream()时会出现IllegalStateException

  • 现在作为这个问题的解决方案,正如一些人所指出的那样,将此代码移动到一个servlet中,在那里您可以完全控制并按照您想要的方式使用输出流。

这是一个带有scriplet的JSP,它被转换为Servlet文件。 您不需要显式调用响应对象。 如果您需要查看编译后的JSP在部署时的样子,搜索(Google)如何在服务器上查找已编译的类(由JSP生成的Servlet)。 由于您已经在响应上调用了方法,因此第二次调用在响应对象上是非法的