+-
获取异常-java.lang.IllegalStateException:已为此响应调用了getOutputStream()
我是jsp的新手,当我尝试通过一些名为cId和passWord的参数调用jsp页面时,我收到此错误,我一直在尝试的代码如下,我已经经历了同样的错误,谷歌搜索,但我仍然遇到同样的问题.
代码是:

<body>
        <%

        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 = "<smsreport>"
                    + "<date>" + time + "</date>"
                    + "<result>" + "SUCESS" + "</result>"
                    + "<msgid>" + currentTimeMillis() + "</msgid>"
                    + "<msgparts>" + "1" + "</msgparts>"
                    + "</smsreport>";

            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 = "<smsreport>"
                    + "<date>" + time + "</date>"
                    + "<result>ERROR</result>"
                    + "<msgid>" + "ErrorCode" + "</msgid>"
                    + "<msgparts>" + "ErrorMessage" + "</msgparts>"
                    + "</smsreport>";

            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);
            }

        }
    %>
</body>
最佳答案
您不应该尝试在JSP中执行此操作. JSP已经获得了输出流来写入它的输出.您需要使用servlet来返回XML.

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

点击查看更多相关文章

转载注明原文:获取异常-java.lang.IllegalStateException:已为此响应调用了getOutputStream() - 乐贴网