一、應用背景
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同時放在第一行即可,一個接一個的後面。雖然不好看,但是解決問題哦