日期:2014-05-16  浏览次数:20445 次

jQuery+json+servlet 动态取后台数据

使用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);
		
		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"}]
		*/
		response.getWriter().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"}]}
		  response.getWriter().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 +