JSP 輸出 XML,Firefox 報「XML 解析錯誤:XML 或文本聲明不在實體的開頭」,Chrome 報「XML declaration allowed only at the start of the document」。
XML 宣告 `` **必須位於檔案第 1 行第 1 字元**,前面不能有任何空白、換行、BOM、JSP 指令輸出。
典型錯誤寫法:
<%@ page contentType="text/xml;charset=UTF-8" %>
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<?xml version="1.0" encoding="UTF-8"?>
<root>...</root>
JSP 指令雖不輸出內容,但編譯後的 Servlet 可能在 `out.write()` 前寫入換行或空白,導致 XML 宣告前移。
<%@ page contentType="text/xml;charset=UTF-8" %><%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %><?xml version="1.0" encoding="UTF-8"?><root><c:forEach items="${list}" var="item"><item id="${item.id}"><title>${item.title}</title></item></c:forEach></root>
雖然閱讀性差,但**保證 XML 宣告位於輸出流最開頭**。
JSP 終究是為 HTML 設計,輸出純 XML 時 Servlet 更可控:
@WebServlet("/api/data.xml")
public class XmlServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/xml;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.println("");
out.println("");
// 遍歷寫入...
out.println(" ");
}
}