我想在我的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;
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。