2013-02-19 132 views
0

我是新来的JSP,当我尝试调用名为CID和密码的一些参数一个jsp页面,我得到这个错误,我一直在尝试的代码在下面给出,我已经经历了使用谷歌搜索看到的同样的错误,但我仍然遇到同样的问题。 代码是:获取异常java.lang.IllegalStateException:getOutputStream方法()已经被调用,这种响应

<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> 

回答

0

您不应该在JSP内部尝试这样做。 JSP已经获得了一个输出流来写它的输出。你需要使用一个servlet来返回你的XML。

当你调用response.getOutputStream,它与该JSP(这将汇编成一个servlet)已经获得的输出流的事实相矛盾。这就是它导致IllegalStateException的原因。

1

这是一个将scriplet转换为Servlet文件的JSP。您不需要显式调用响应对象。如果您需要了解已部署的已编译JSP的外观,请搜索(Google)如何查找服务器上已编译的类(由JSP生成的Servlet)。既然你已经呼吁应对方法的第二次调用是响应对象

2

抛出IllegalStateException - 如果此响应已调用getWriter方法。

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

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

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

相关问题