Whitespace before XML declaration from JSP

2019-06-10 02:51发布

I'm trying to achieve full XHTML transitional validation of my JSP output but I've hit a snag. The top of the header looks like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

It is included with a statement that looks like this:

<jsp:include>
  <jsp:attribute name="page"><owportal:page name="/style/portal/header.jsp" /></jsp:attribute>
</jsp:include>

The <owportal:page> tag checks a few different paths so that we can override it with a project-specific header if need be. The problem with this is the owportal taglib needs to be declared before it can be used, inserting a blank line before the XML declaration and causing a validation warning.

I have tried using jsp:output to generate an XML declaration without much luck. Can anyone let me know if I'm on the right track here?

Update:

Currently I'm trying something like this

<%@ taglib uri="/WEB-INF/yadda/yadda" prefix="yadda" %>

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns="http://www.w3.org/1999/xhtml" version="2.0">
  <jsp:output omit-xml-declaration="false" doctype-root-element="html"
              doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
              doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
</jsp:root>

<html>...

And I am getting an error "Invalid standard action" at the <jsp:root> line. Not the most helpful error message. Sounds like I'm using the tag wrong somehow perhaps. I'm running Tomcat 6 so it shouldn't be a problem with the JSP version. Can anyone see what I'm doing wrong? Is <jsp:root> meant to wrap around <html>?

1条回答
甜甜的少女心
2楼-- · 2019-06-10 03:42

If I understand you correctly, then you are trying to include this jsp:include at the very top of the JSP, but, in the process, you are causing the JSP to output a few bits of whitespace at the top before the XML preamble.

In cases like this, I have just resorted to making sure the JSP has no whitespace up there:

<jsp:include><jsp:attribute name="page"><owportal:page name="/style/portal/header.jsp" /></jsp:attribute></jsp:include>[your content continues here, not on next line!]...

But I think you are kind of asking a different question, which is how to tell a JSP to output an XML declaration. To do that, you want to start with something like this (assuming here you're using a recent JSP spec like 2.1)...

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns="http://www.w3.org/1999/xhtml" version="2.1">
  <jsp:output
          omit-xml-declaration="false" doctype-root-element="html"
          doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
          doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>
...

This is the more right way to handle outputting XML from a JSP(X) file -- more explicit.

查看更多
登录 后发表回答