使用jQuery+json+servlet动态取后台的list集合的数据。
需要引入json相关的jar包(见附件)
项目结构见附件图
后台servlet:
package com.cxl.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.cxl.model.User;
public class UserServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//禁用缓存,确保网页信息是最新数据
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", -10);
PrintWriter out = response.getWriter();
System.out.println(System.currentTimeMillis());
List<User> users = new ArrayList<User>();
User user = new User();
user.setUsername("cxl");
user.setPassword("123");
User u = new User();
u.setUsername("lhl");
u.setPassword("1234");
users.add(user);
users.add(u);
//List转json数组格式
JSONArray jsonArray = JSONArray.fromObject(users);
System.out.println(jsonArray.toString());
/*
打印结果为:[{"password":"123","username":"cxl"}
,{"password":"1234","username":"lhl"}]
*/
out.print(jsonArray.toString());
/*
用json对象格式返回数据
JSONObject jsonObj = new JSONObject();
jsonObj.put("users", users);
System.out.println(jsonObj);
打印结果:{"users":[{"password":"1234","username":"cxl"}
,{"password":"1234","username":"lhl"}]}
out.print(jsonObj);
*/
out.flush();
out.close();
}
}
在web.xml中配相应的映射
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>UserServlet</servlet-name> <servlet-class>com.cxl.servlet.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/servlet/UserServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
js文件:
//jQuery(function{})或$(document).ready(function(){})或$(function(){}); jQuery(function() { setTimeout(getUserInfo,0);//执行getUserInfo函数一次 function getUserInfo() { $.post("http://localhost:8080/jQueryDemo/servlet/UserServlet",null, function call(data){ var str = ""; str = "<table><tr><th>用户名</th><th>密码</th></tr>"; //循环遍历json数组格式的数据 $.each(data, function(index, item) { str += "<tr><td>" + item.username + "</td><td>" + item.password + "</td></tr>"; }); /* 循环遍历json对象格式的数据 $.each(data.users, function(index, item) { str += "<tr><td>" + item.username + "</td><td>“ + item.password + "</td></tr>"; }); */ str += "</table>"; //把数据展现在jsp页面上 $("#userInfo").html(str); },"json"); }; //动态取后台数据 setInterval(getUserInfo, 10000);//每隔10秒钟执行一次getUserInfo函数 });
show.jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.7.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/userInfo.js"></script>
</head>
<body>
<center>
<h2>用户信息</h2>
<div id="userInfo"></div>
</center>
</body>
</html>