JSP中拚裝數據為XML出現的問題
一、應用背景
JSP取得Servlet中放入request的List,將List中的數據拚裝成XML。以下代碼在Eclipse的內置瀏覽器中顯示為xml,沒有問題。
/** * 新聞Servlet * @author 徐越 * */ public class ListServlet extends HttpServlet { private static final long serialVersionUID = 1L; private VideoNewsService vs = new VideoNewsServiceImpl(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<VideoNews> news = vs.readNews(); request.setAttribute("lstnews", news); request.getRequestDispatcher("/WEB-INF/pages/news.jsp").forward(request, response); } }
<%@ page language="java" contentType="text/xml; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %> <?xml version="1.0" encoding="UTF-8"?> <videoNews> <c:forEach items="${lstnews}" var="n"> <news > <title>${n.title }</title> <length>${n.timeLength }</length> </news> </c:forEach> </videoNews>
二、發現問題
火狐中報錯:XML解析錯誤:XML 或文本聲明不在實體的開頭
chrome報錯:XML declaration allowed only at the start of the document
根據錯誤信息,可以知道XML聲明<?xml version="1.0" encoding="UTF-8"?>必須在文檔的開頭。
三、解決問題
方法一
將page、taglib、xml同時放在第一行即可,一個接一個的後麵。雖然不好看,但是解決問題哦。
方法二
有網友朋友給出好的方法,在jsp首行放置<%@ page trimDirectiveWhitespaces="true"%>
最後更新:2017-04-03 07:57:30