servlet+json示例

1、servlet部分

 

@WebServlet("/index")
public class IndexServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/x-javascript;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        TableServer server = new TableServer();
        List<Table> models = server.getAllTables();
        if (models != null && models.size() > 0) {
            //构造json对象
            StringBuffer json = new StringBuffer();
            json.append("[");
            for (Table model : models) {
                json.append('{');
                json.append("people:").append(model.getPeople()).append(",");
                json.append("status:").append(model.getTable_status()).append(",");
                json.append("tableName:").append("'").append(model.getTable_name().trim()).append("'");
                json.append("},");
            }
            json.deleteCharAt(json.length() - 1);
            json.append("]");
            out.println(json.toString());
            out.close();
        } else {
            out.println("[{id:0,name:''}]");
            out.close();
        }
	}
}

 

2、前台页面解析

var url="index";
$.get(url, null, function(data){
       var objs=eval("("+data+")"); //解析json对象
       for(var i=0;i<objs.length;i++){
    	   upTables = addTable(objs[i].people,upTables,c_index,objs[i].tableName,objs[i].status);
       }
 });

3、table对象

 

public class Table {
	final static int MAX_PEOPLE = 12;
	final static int MIN_PEOPLE = 2;
	private int table_id;
	private int table_status; 
	private int people;
	
	public String getTable_name() {
		return table_name;
	}
	public void setTable_name(String table_name) {
		this.table_name = table_name;
	}
	private String table_name;
	
	public int getTable_id() {
		return table_id;
	}
	public void setTable_id(int tableId) {
		table_id = tableId;
	}
	public int getTable_status() {
		return table_status;
	}
	public void setTable_status(int tableStatus) {
		table_status = tableStatus;
	}
	public int getPeople() {
		return people;
	}
	public void setPeople(int people) {
		this.people = people;
	}
}

 

你可能感兴趣的:(servlet)