Java 是否可以在jsp中根据条件设置页面内容类型,或者为单个jsp设置不同的内容类型
我想使用单个jsp页面显示JSON和XML。 一次只有一个属性来自java类。 我的代码是这样的Java 是否可以在jsp中根据条件设置页面内容类型,或者为单个jsp设置不同的内容类型,java,xml,json,jsp,Java,Xml,Json,Jsp,我想使用单个jsp页面显示JSON和XML。 一次只有一个属性来自java类。 我的代码是这样的 <% String json = (String) request.getAttribute("userRequestedJsonById"); if (!StringUtility.isNullOrEmpty(json)) {%> <%=json%> <% } else { %>
<%
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 set content type是如何工作的,有没有其他方法可以做到这一点,或者限制在特定条件下设置content type xml
谢谢。在打印任何内容之前,都需要设置内容类型,因此您需要摆脱导致打印空白的标签的无意义打开和关闭。然后您将使用
response.setContentType()
:
如果您要使用Scriptlets保持代码块打开,并使用out.print()
而不是打开、关闭、然后再打开,那么它也会更干净。那太不可读了 尝试使用
。我还没试过。但是,还是。试试看:)
<%
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);
}
}
%>