【问题标题】:is it possible to set page content type on a condition in jsp or to set different content type for a single jsp是否可以在 jsp 中的条件下设置页面内容类型或为单个 jsp 设置不同的内容类型
【发布时间】:2014-05-25 04:39:14
【问题描述】:

我想使用单个 jsp 页面显示 JSON 和 XML。 一次只有一个属性来自 java 类。 我的代码看起来像这样。

<%
        String json = (String) request.getAttribute("userRequestedJsonById");
        if (!StringUtility.isNullOrEmpty(json)) {%>
            <%=json%>
        <% } else { %>
            <%
            String xml = (String) request.getAttribute("searcherRespondedXmlById");
            if(!StringUtility.isNullOrEmpty(xml)) {%>
                <%@page contentType="text/xml"%>
                <%=xml%>
            <%}%>
        <%}%>

我有一个名为 JSONVIEW 的插件来正确显示 json。如果它找到内容类型 xml,它将不起作用。 内容类型仅在条件上设置,jsp 包含此内容类型,即使条件不满足。 我不太了解 jsp 设置内容类型的工作原理,有没有其他方法可以做到这一点或限制在特定条件下设置内容类型 xml。

谢谢。

【问题讨论】:

  • 尝试使用&lt;%@page contentType="text/xml;application/json"%&gt;。我没试过。但是,还是。试一试:)

标签: java xml json jsp


【解决方案1】:

设置内容类型需要在打印任何内容之前完成,因此您需要摆脱导致打印空白的标签的无意义的打开和关闭。然后你将使用response.setContentType():

<%
   String json = (String) request.getAttribute("userRequestedJsonById");
   if (!StringUtility.isNullOrEmpty(json)) 
   {
       response.setContentType("application/json");
       out.print(json);
   }
   else 
   {
       String xml = (String) request.getAttribute("searcherRespondedXmlById");
       if(!StringUtility.isNullOrEmpty(xml)) 
       {
          response.setContentType("text/xml");
          out.print(xml);
       }
   }
%>

如果您打算使用 Scriptlet 保持代码块打开并使用 out.print() 而不是打开、关闭然后 并再次打开,它也更简洁。简直太难读了。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2012-10-19
    • 2010-12-27
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多