Ajax发送Json数据及解析

上一篇文章写了前端和后台用xml进行通信,这次写试用json来进行通信。

这两个都是前后端进行交互的较好的方式,具体区别,不懂得可自行百度。这里推荐一篇文章(里面总结的也是比较全的):

http://www.cnblogs.com/SanMaoSpace/p/3139186.html


Json串格式:json数据格式:[{id:"U001",name:"Tom",age:19},{id:"U002",name:"Mike",age:22},{.....},{....}]


前端:

ajaxJson.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


	
		
		ajax-json技术演示
		
	
	
		传统页面数据查询方式









后台:

JsonServlet0.java    本servlet主要是演示利用传统方式ajax接收后台发送的数据发现:从前台发送过来的数据可以看出是整个HTML文档。而实际是对我们有用只有几个user对象信息,信息太多冗余。而且以HTML方式收到的数据,在前台解析也非常麻烦,因此要使用ajax-json技术 

package cn.hncu.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.domain.User;

@WebServlet("/JsonServlet0")
public class JsonServlet0 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//按理应该调用service和dao到数据库中查询,这里省略了.
		List users=new ArrayList();
		users.add(new User("U001","Tom",19));
		users.add(new User("U002","Mike",22));
		users.add(new User("U003","apple",25));
		users.add(new User("U004","彰武",29));
		
		request.setAttribute("users", users);
		request.getRequestDispatcher("/jsps/user.jsp").forward(request, response);
	}

}


传统方式接收数据:可以看到很多是没用的消息

Ajax发送Json数据及解析_第1张图片



JsonServlet1.java   本servlet采用了手动封装json字符串,虽然也实现了json,但是有点麻烦

package cn.hncu.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.domain.User;

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//按理应该调用service和dao到数据库中查询,这里省略了.
		List users=new ArrayList();
		users.add(new User("U001","Tom",19));
		users.add(new User("U002","Mike",22));
		users.add(new User("U003","apple",25));
		users.add(new User("U004","彰武",29));
		
		//在后台手动将user数据封装成json数据格式串,发送到前端
		//json数据格式:[{id:"U001",name:"Tom",age:19},{id:"U002",name:"Mike",age:22},{.....},{....}]
		String json="[";
		int temp=0;
		for(User user:users){
			if(temp==0){
				json+="{id:\""+user.getId()+"\",name:\""+user.getName()+"\",age:"+user.getAge()+"}";
				temp++;
			}else{
				json+=",{id:\""+user.getId()+"\",name:\""+user.getName()+"\",age:"+user.getAge()+"}";
			}
		}
		json+="]";
		System.out.println(json);
		
		//发送到前端
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(json);
	}

}



JsonServlet2.java    本servlet采用了apache工具来进行对数据的转换

package cn.hncu.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.domain.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//按理应该调用service和dao到数据库中查询,这里省略了.
		List users=new ArrayList();
		users.add(new User("U001","Tom",19));
		users.add(new User("U002","Mike",22));
		users.add(new User("U003","apple",25));
		users.add(new User("U004","彰武",29));
		
		//在后台利用apache工具将List数据封装成json数据格式串,发送到前端
		//json数据格式:[{id:"U001",name:"Tom",age:19},{id:"U002",name:"Mike",age:22},{.....},{....}]
		//转    List--Json
		JSONArray jsonObj=JSONArray.fromObject(users);
		String json=jsonObj.toString();
		System.out.println(json);
		
		Map map=new HashMap();
		map.put("id", "P001");
		map.put("name", "李明");
		map.put("age", 25);
		map.put("addr", "中国");
		map.put("addr", "男");
		map.put("friend", new User("U110", "Jack", 26));
		JSONObject obj=JSONObject.fromObject(map);
		System.out.println(obj.toString());
		
		//发送到前端
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(json);
	}

}



JsonServlet3.java    本例是采用了阿里巴巴研发的工具来对要发往前端的数据进行封装。(终于用到了本国的工具,还有点小激动\(≧▽≦)/)

package cn.hncu.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;

import cn.hncu.domain.User;

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//按理应该调用service和dao到数据库中查询,这里省略了.
		List users=new ArrayList();
		users.add(new User("U001","Tom",19));
		users.add(new User("U002","Mike",22));
		users.add(new User("U003","apple",25));
		users.add(new User("U004","彰武",29));
		
		//在后台利用fastjon工具将List数据封装成json数据格式串,发送到前端
		//json数据格式:[{id:"U001",name:"Tom",age:19},{id:"U002",name:"Mike",age:22},{.....},{....}]
		//转    List--Json
		String json=JSONArray.toJSONString(users);
		System.out.println(json);
		
		Map map=new HashMap();
		map.put("id", "P001");
		map.put("name", "李明");
		map.put("age", 25);
		map.put("addr", "中国");
		map.put("sex", "男");
		map.put("friend", new User("U110", "Jack", 26));
		String json2=JSONArray.toJSONString(map);
		System.out.println(json2);
		
		//发送到前端
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(json);
	}

}

这里用到了一个值对象User.java

package cn.hncu.domain;

public class User {
	private String id;
	private String name;
	private Integer age;
	
	
	public User() {
	}
	public User(String id, String name, Integer age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
}


以上三种方法都成功地实现了利用Json通信。(这里贴出其中一个结果)

Ajax发送Json数据及解析_第2张图片

你可能感兴趣的:(JavaWeb开发技术,Java从入门到高级编程)