解決JSP中拼裝資料為XML出現的問題

來源:互聯網
上載者:User

 一、應用背景

JSP取得Servlet中放入request的List,將List中的資料拼裝成XML。以下代碼在Eclipse的內建瀏覽器中顯示為xml,沒有問題。

[java]
/**
* 新聞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);
}
}

/**
* 新聞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);
}
}
[html]
<%@ page language="java" contentType="text/xml; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<?xml version="1.0" encoding="UTF-8"?>
<videoNews>
<c:forEach items="${lstnews}" var="n">
<news id="${n.id }">
<title>${n.title }</title>
<length>${n.timeLength }</length>
</news>
</c:forEach>
</videoNews>

<%@ page language="java" contentType="text/xml; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<?xml version="1.0" encoding="UTF-8"?>
<videoNews>
<c:forEach items="${lstnews}" var="n">
<news id="${n.id }">
<title>${n.title }</title>
<length>${n.timeLength }</length>
</news>
</c:forEach>
</videoNews>

 

二、發現問題

Firefox中報錯:XML解析錯誤:XML 或文本聲明不在實體的開頭

chrome報錯:XML declaration allowed only at the start of the document

根據錯誤資訊,可以知道XML聲明<?xml version="1.0" encoding="UTF-8"?>必須在文檔的開頭。


三、解決問題

將page、taglib、xml同時放在第一行即可,一個接一個的後面。雖然不好看,但是解決問題哦

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.