我想在我的web項目(struts2+hibernate)的首頁的頁面輸出數據庫的News這個表的內容,請問具體的代碼是怎樣的,我都快點瘋了。
附我自己寫的代碼,及供參考,可忽略
在servlet中:
public void getNewsList(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/xml"); // 設置響應類型為XML
response.setCharacterEncoding("GBK"); //設置響應的編碼方式
PrintWriter out = response.getWriter();
ConnDB conn=new ConnDB();
String sql="SELECT * FROM News";
ResultSet rs=conn.executeQuery(sql); //
List newsList=new ArrayList();
try {
News n=new News();
while(rs.next()){
n.setId(rs.getInt("id"));
n.setTitle(rs.getString("title"));
newsList.add(n);
}
} catch (SQLException e) {
e.printStackTrace();
}
conn.close(); //
/****************通過Dom4j將獲取的最新用戶信息輸出到XML文檔中****************/
Document document = DocumentHelper.createDocument();
Element returnValue= document.addElement("returnValue");
document.setRootElement(returnValue); // 將returnValue設置為根節點
Element e_newsList=returnValue.addElement("NewsList"); //添加newUser節點
e_newsList.setData(newsList);
XMLWriter output;。。。。。
output.flush();
}
在JSP頁面中:
javascript中:
function getUserInfo(){
var loader_List=new net.AjaxRequest("NewsListServlet?action=getNewsList&nocache="+new Date().getTime(),deal_getNewsList,onerror,"GET");//實例化Ajax對象
}
function deal_getNewsList(){
var objXml=this.req.responseXML; //獲取返回的XML數據
var newsList = objXml.getElementsByTagName("newsList")[0].firstChild.data; //獲取
document.getElementById("newsList").innerHTML=newsList; //顯示
}
timer=window.setInterval(getUserInfo,60000); //每隔1分鐘獲取一次
public void getNewsList(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/xml"); // 設置響應類型為XML
response.setCharacterEncoding("GBK"); //設置響應的編碼方式
PrintWriter out = response.getWriter();
ConnDB conn=new ConnDB();
String sql="SELECT * FROM News";
ResultSet rs=conn.executeQuery(sql); //
List newsList=new ArrayList();
try {
News n=new News();
while(rs.next()){
n.setId(rs.getInt("id"));
n.setTitle(rs.getString("title"));
newsList.add(n);
}
} catch (SQLException e) {
e.printStackTrace();
}
conn.close(); //
response.setHeader("cache-control","no-cache");
PrintWriter out=response.getWriter();
out.print("<?xml version='1.0' encoding='UTF-8'?>");
out.print("<root>");
for(int i=0;i<newList.size();i++){
out.print("<NewList>");
out.print("<Id>")
out.print(newList.get(i).getId());
out.print("</Id>");
out.print("<Title>");
out.print(newList.get(i).getTitle());
out.print("</Title>");
out.print("</NewList>");
}
out.print("</root>");
out.flush;
out.close;