2 kingson wu Kingson_Wu 于 2013.06.08 13:26 提问

如何用Ajax传递一个对象集合到jsp页面。

我想在我的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分钟获取一次

1个回答

u010122579
u010122579   2013.06.08 18:44
已采纳
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;
Kingson_Wu
Kingson_Wu 之前我已经试过很多次其他方法了,都是不行,快疯了,请问这个代码您有测试过吗?谢谢!
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!