java web开发:ajax技术(三)——JSON在服务器和浏览器之间的传递

来源:互联网 发布:ubuntu下ros安装过程 编辑:程序博客网 时间:2024/05/02 01:12

上节内容中,我们介绍了什么是json,并且用一个简单的实例来演示了服务器和客户端之间的数据交互原理。那么,我们在使用json封装数据之后,怎么实现客户端和服务器的数据交互呢?


一 简单json数据传递


简单的JSON数据类型,就是前一章介绍过的JSON的标量格式的数据,比如单个字符串或者数字等等,反映到服务器就是我们java中的8种基本数据类型的数据。

那这样的基本类型的数据传递方式是怎么样的呢?


(1)简单json数据对象——标量的传递和解析——用户键盘输入记录实例


编写服务器代码——SimpleJsonData.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo1;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class SimpleJsonData extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// 设置编码格式req.setCharacterEncoding("gb18030");resp.setContentType("text/html;charset=gb18030");// 获取客户端传递的数据String value = req.getParameter("value");// value的值就是一个简单的JSON标量——单个字符串并写入到返回客户端的响应中PrintWriter out = resp.getWriter();out.write(value);out.flush();out.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doGet(req, resp);}}

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

配置web.xml

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>ajax_0100</display-name>  <!-- 1. 第一个ajax程序:密码拾取器 -->  <servlet>  <servlet-name>simplejsondata</servlet-name>  <servlet-class>demo1.SimpleJsonData</servlet-class>  </servlet>  <servlet-mapping>  <servlet-name>simplejsondata</servlet-name>  <url-pattern>/simplejson.action</url-pattern>  </servlet-mapping>      <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app>

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

编写客户端代码——index.jsp

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%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">// 定义根据id获取标签的方法function $(elementid) {return document.getElementById(elementid);}// 定义获取XMLHttpRequest对象的方法function getXmlHttpObj() {try {return new XMLHttpRequest();} catch (e) {try {return new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {return new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {alert("您的浏览器不支持ajax!");}}}}function recordInput (value) {// 1. 获取XMLHttpRequest对象var xmlHttp = getXmlHttpObj();// 2. 定义处理响应的代码xmlHttp.onreadystatechange = function () {//2.1. 如果服务器成功响应并正确返回数据if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 2.2. 将返回的数据写入到当前页面记录文本输入框$("inputrecord").value = xmlHttp.responseText;}};xmlHttp.open("get", "simplejson.action?value=" + value, true);xmlHttp.send(null);}</script>  </head>    <body>    用户输入:<input type="text" name="username" id="username" onkeyup="recordInput(this.value)"/><br />   输入记录:<input type="text" name="inputrecord" id="inputrecord"/><br />  </body></html>


~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

测试

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

运行web项目

打开浏览器,访问项目主页

出现提示用户输入信息和对应的文本数据狂

用户输入数据后,在下面的记录输入框中出现用户输入的数据

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

(2)简单JSON数据对象——序列(数组)的传递和解析——班级学生自动查看实例

编写服务器代码——SimpleJsonArrayData.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo2;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;public class SimpleJsonArrayData extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// 设置编码格式req.setCharacterEncoding("gb18030");resp.setContentType("text/html;charset=gb18030");// 获取客户端传递的数据String value = req.getParameter("value");// 定义JSON序列——数组并写入到返回客户端的响应中String [] stus = new String[3];if("class1".equals(value)) {stus[0] = "章俕";stus[1] = "里斯";stus[2] = "汪武";} else if("class2".equals(value)) {stus[0] = "宋柳";stus[1] = "赵驷";stus[2] = "黎斯";} else {stus = null;}// 将数据对象转换成json数据JSONArray json = JSONArray.fromObject(stus);PrintWriter out = resp.getWriter();out.write(json.toString());out.flush();out.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doGet(req, resp);}}


~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

配置web.xml

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>ajax_0100</display-name>  <servlet>  <servlet-name>simplejsonarraydata</servlet-name>  <servlet-class>demo2.SimpleJsonArrayData</servlet-class>  </servlet>  <servlet-mapping>  <servlet-name>simplejsonarraydata</servlet-name>  <url-pattern>/simplejsonarray.action</url-pattern>  </servlet-mapping>    <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app>


~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

编写客户端代码——index2.jsp

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%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">// 定义根据id获取标签的方法function $(elementid) {return document.getElementById(elementid);}// 定义获取XMLHttpRequest对象的方法function getXmlHttpObj() {try {return new XMLHttpRequest();} catch (e) {try {return new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {return new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {alert("您的浏览器不支持ajax!");}}}}function chkStuInfo (value) {// 1. 获取XMLHttpRequest对象var xmlHttp = getXmlHttpObj();// 2. 定义处理响应的代码xmlHttp.onreadystatechange = function () {//2.1. 如果服务器成功响应并正确返回数据if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 2.2. 将返回的数据转换成json数据var stus = xmlHttp.responseText;var stuJson = eval(stus);// 2.3. 将数据写入到html指定的标签中$("stu1").innerText = stuJson[0];$("stu2").innerText = stuJson[1];$("stu3").innerText = stuJson[2];}};xmlHttp.open("get", "simplejsonarray.action?value=" + value, true);xmlHttp.send(null);}</script>  </head>    <body>    输入班级:<input type="text" name="username" id="username" onblur="chkStuInfo(this.value)"/><br />   学生列表:   <span id="stu1"></span>   <span id="stu2"></span>   <span id="stu3"></span>  </body></html>


~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

测试

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

运行项目

打开浏览器,访问index2.jsp页面

在打开的浏览器窗口中,出现提示输入查看班级信息

在后面的输入框中输入class1,在后面的提示信息中出现1班学生的信息

在后面的输入框中输入class2,在后面的提示信息中出现2班学生的信息

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~


简单数据类型的Json数据,其实反映到javaScript中,不需要解析直接可以按照需求进行使用即可


二 简单对象数据传递


解决了java基本类型的数据的传递之后,那么对于java来说,基本类型只是构建对象的基石,在java中用到的最多的都是使用Java类封装的对象

问:

那么对象类型的数据怎么进行封装?

封装完成的json怎么传递达到客户端?

在客户端怎么解析这样的对象数据呢?

答:

对象类型的数据,使用JSONArray进行解析封装

json数据,通过客户端的请求,响应到客户端(不区分是普通请求还是ajax请求)

JavaScript解析json使用函数eval(jsondata)将json字符转换成javaScript中的Json对象

示例如下:


(1)简单对象数据——java实例对象的传递和解析——用户信息查看器


服务器端实体类开发——User.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo3;/** * 用户实体类 * @author ZuoYi * */public class User {private int id;// 用户编号private String name;// 用户姓名private int age;// 用户年龄private String gender;// 用户性别private String regNo;// 用户身份证号码public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getRegNo() {return regNo;}public void setRegNo(String regNo) {this.regNo = regNo;}public User(int id, String name, int age, String gender, String regNo) {super();this.id = id;this.name = name;this.age = age;this.gender = gender;this.regNo = regNo;}public User() {super();}}


~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

服务器端servlet开发——SimpleJavaObject.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo3;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;public class SimpleJavaObjectData extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// 设置编码格式req.setCharacterEncoding("gb18030");resp.setContentType("text/html;charset=gb18030");// 获取客户端传递的数据String value = req.getParameter("value");// 定义JSON映射——对象并写入到返回客户端的响应中User user = null;if("zhangsan".equals(value)) {user = new User(1, "zhangsan" , 23 , "男" , "62252119911212087x");} else if("lisi".equals(value)) {user = new User(2, "lisi" , 14 , "女" , "62252200012120879");} else {user = null;}// 将数据对象转换成json数据JSONArray json = JSONArray.fromObject(user);PrintWriter out = resp.getWriter();out.write(json.toString());out.flush();out.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doGet(req, resp);}}

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

web.xml配置

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>ajax_0100</display-name>  <servlet>  <servlet-name>simplejavaobjectdata</servlet-name>  <servlet-class>demo3.SimpleJavaObjectData</servlet-class>  </servlet>  <servlet-mapping>  <servlet-name>simplejavaobjectdata</servlet-name>  <url-pattern>/simplejavaobject.action</url-pattern>  </servlet-mapping>    <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app>

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

视图开发——index3.jsp

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%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">// 定义根据id获取标签的方法function $(elementid) {return document.getElementById(elementid);}// 定义获取XMLHttpRequest对象的方法function getXmlHttpObj() {try {return new XMLHttpRequest();} catch (e) {try {return new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {return new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {alert("您的浏览器不支持ajax!");}}}}function chkUserInfo (value) {// 1. 获取XMLHttpRequest对象var xmlHttp = getXmlHttpObj();// 2. 定义处理响应的代码xmlHttp.onreadystatechange = function () {//2.1. 如果服务器成功响应并正确返回数据if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 2.2. 将返回的数据转换成json数据var user = xmlHttp.responseText;var userJson = eval(user)[0];// 获取数据中的一个元素// 2.3. 将数据写入到html指定的标签中$("uid").innerText = userJson.id;$("uname").innerText = userJson.name;$("uage").innerText = userJson.age;$("uregno").innerText = userJsonuregno;}};xmlHttp.open("get", "simplejavaobject.action?value=" + value, true);xmlHttp.send(null);}</script>  </head>    <body>    输入用户姓名:<input type="text" name="username" id="username" onblur="chkUserInfo(this.value)"/><br />   用户编号:<span id="uid"></span>   用户姓名:<span id="uname"></span>   用户年龄:<span id="uage"></span>   用户性别:<span id="ugender"></span>   用户身份证:<span id="uregno"></span>  </body></html>

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

测试

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

运行项目

打开浏览器,访问服务器的index3.jsp页面

在页面中输入用户姓名,如:zhangsan/lisi

然后在光标离开输入框之后,在输入框的下方动态显示用户信息

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~


这里测试用例中只是封装了一个单个的实体类对象,在java中常见的实体类对象之间常常会出现组合关系,那么具有组合关系的实体类的数据怎么进行传递和解析呢?


三复杂对象数据传递

复杂对象——java中组合实例对象数据的传递和解析

服务器端实体类开发——Address.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo3;/** * 用户地址信息 *  * @author ZuoYi *  */public class Address {private int id;// 编号private String pro;// 省private String city;// 市public int getId() {return id;}public void setId(int id) {this.id = id;}public String getPro() {return pro;}public void setPro(String pro) {this.pro = pro;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Address(int id, String pro, String city) {super();this.id = id;this.pro = pro;this.city = city;}public Address() {super();}}

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

服务器端实体类开发——User.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo3;/** * 用户实体类 *  * @author ZuoYi *  */public class User {private int id;// 用户编号private String name;// 用户姓名private int age;// 用户年龄private String gender;// 用户性别private String regNo;// 用户身份证号码private Address addr;// 用户地址public Address getAddr() {return addr;}public void setAddr(Address addr) {this.addr = addr;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getRegNo() {return regNo;}public void setRegNo(String regNo) {this.regNo = regNo;}public User(int id, String name, int age, String gender, String regNo,Address addr) {super();this.id = id;this.name = name;this.age = age;this.gender = gender;this.regNo = regNo;this.addr = addr;}public User() {super();}}

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

服务器端servlet开发——JavaObjectGroup.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo3;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;public class JavaObjectGroup extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// 设置编码格式req.setCharacterEncoding("gb18030");resp.setContentType("text/html;charset=gb18030");// 获取客户端传递的数据String value = req.getParameter("value");// 定义JSON映射——对象并写入到返回客户端的响应中System.out.println(value);User user = null;if("zhangsan".equals(value)) {System.out.println("====" + value);Address addr = new Address(1 , "甘肃" , "兰州");user = new User(1, "zhangsan" , 23 , "男" , "62252119911212087x",addr);} else if("lisi".equals(value)) {Address addr = new Address(1 , "甘肃" , "西安");user = new User(2, "lisi" , 14 , "女" , "62252200012120879",addr);} else {user = null;}// 将数据对象转换成json数据JSONArray json = JSONArray.fromObject(user);PrintWriter out = resp.getWriter();out.write(json.toString());out.flush();out.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doGet(req, resp);}}

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

web.xml配置

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">    <servlet>  <servlet-name>javaobjectgroup</servlet-name>  <servlet-class>demo4.JavaObjectGroup</servlet-class>  </servlet>  <servlet-mapping>  <servlet-name>javaobjectgroup</servlet-name>  <url-pattern>/javaobjectgroups.action</url-pattern>  </servlet-mapping>    <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app>

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

视图开发——index4.jsp

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%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">// 定义根据id获取标签的方法function $(elementid) {return document.getElementById(elementid);}// 定义获取XMLHttpRequest对象的方法function getXmlHttpObj() {try {return new XMLHttpRequest();} catch (e) {try {return new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {return new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {alert("您的浏览器不支持ajax!");}}}}function chkUserInfo (value) {// 1. 获取XMLHttpRequest对象var xmlHttp = getXmlHttpObj();// 2. 定义处理响应的代码xmlHttp.onreadystatechange = function () {//2.1. 如果服务器成功响应并正确返回数据if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 2.2. 将返回的数据转换成json数据var user = xmlHttp.responseText;var userJson = eval(user)[0];// 获取数据中的一个元素// 2.3. 将数据写入到html指定的标签中$("uid").innerText = userJson.id;$("uname").innerText = userJson.name;$("uage").innerText = userJson.age;$("uregno").innerText = userJson.regNo;$("address").innerText = userJson.addr.pro + userJson.addr.city;};};xmlHttp.open("get", "javaobjectgroups.action?value=" + value, true);xmlHttp.send(null);}</script>  </head>    <body>    输入用户姓名:<input type="text" name="username" id="username" onblur="chkUserInfo(this.value)"/><br />   用户编号:<span id="uid"></span>   用户姓名:<span id="uname"></span>   用户年龄:<span id="uage"></span>   用户性别:<span id="ugender"></span>   用户身份证:<span id="uregno"></span>   用户地址:<span id="address"></span>  </body></html>

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

测试

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

运行项目

打开浏览器,访问服务器的index3.jsp页面

在页面中输入用户姓名,如:zhangsan/lisi

然后在光标离开输入框之后,在输入框的下方动态显示包含地址信息的用户信息

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~


在实际项目开发中,服务器和客户端的数据交互,除了这种简单的标量、java的单个实体类对象、组合的java实体类对象的传递之外,最常见的还有对象的集合的传递方式,那么这样的集合的传递方式,在我们实际使用中,应该怎么样通过json进行传递和使用呢?


四 集合对象数据传递

(1)集合中包装简单数据类型的数据的传递和解析

服务器端实体类开发——User.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo5;/** * 用户实体类 *  * @author ZuoYi *  */public class User {private int id;// 用户编号private String name;// 用户姓名private int age;// 用户年龄private String gender;// 用户性别private String regNo;// 用户身份证号码public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getRegNo() {return regNo;}public void setRegNo(String regNo) {this.regNo = regNo;}public User(int id, String name, int age, String gender, String regNo) {super();this.id = id;this.name = name;this.age = age;this.gender = gender;this.regNo = regNo;}public User() {super();}}

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~


服务器端servlet开发——JavaObjectList.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package demo5;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;public class JavaObjectList extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// 设置编码格式req.setCharacterEncoding("gb18030");resp.setContentType("text/html;charset=gb18030");// 获取客户端传递的数据String value = req.getParameter("value");// 定义JSON映射——对象并写入到返回客户端的响应中ArrayList<User> ulist = new ArrayList<User>();if("class1".equals(value)) {User user1 = new User(1, "zhangsan" , 23 , "男" , "62252119911212087x");User user2 = new User(2, "zhangsan" , 22 , "男" , "62252119911212087x");User user3 = new User(3, "zhangsan" , 34 , "男" , "62252119911212087x");ulist.add(user1);ulist.add(user2);ulist.add(user3);} // 将数据对象转换成json数据JSONArray json = JSONArray.fromObject(ulist);PrintWriter out = resp.getWriter();out.write(json.toString());out.flush();out.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doGet(req, resp);}}

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

web.xml配置

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <servlet>      <servlet-name>javaobjectlist</servlet-name>      <servlet-class>demo5.JavaObjectList</servlet-class>  </servlet>  <servlet-mapping>      <servlet-name>javaobjectlist</servlet-name>      <url-pattern>/javaobjectlists.action</url-pattern>  </servlet-mapping>   <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app>


~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

视图开发——index5.jsp

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%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">// 定义根据id获取标签的方法function $(elementid) {return document.getElementById(elementid);}// 定义获取XMLHttpRequest对象的方法function getXmlHttpObj() {try {return new XMLHttpRequest();} catch (e) {try {return new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {return new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {alert("您的浏览器不支持ajax!");}}}}function chkUserInfo (value) {// 1. 获取XMLHttpRequest对象var xmlHttp = getXmlHttpObj();// 2. 定义处理响应的代码xmlHttp.onreadystatechange = function () {//2.1. 如果服务器成功响应并正确返回数据if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 2.2. 将返回的数据转换成json数据var users = xmlHttp.responseText;// 返回的是一个用户列表,是json映射数组,获取数组长度var userslength = eval(users).length;var usersList = eval(users);// 2.3. 循环将数据写入到html指定的标签中for(var index = 0; index < userslength; index++){var userid = document.createElement("div");// 创建一个标签userid.setAttribute("id", "uid");var username = document.createElement("div");// 创建一个标签username.setAttribute("id", "uname");var userage = document.createElement("div");// 创建一个标签userage.setAttribute("id", "uage");var usergender = document.createElement("div");// 创建一个标签usergender.setAttribute("id", "ugender");var userregno = document.createElement("div");// 创建一个标签userregno.setAttribute("id", "uregno");$("userinfolist").appendChild(userid);$("userinfolist").appendChild(username);$("userinfolist").appendChild(userage);$("userinfolist").appendChild(usergender);$("userinfolist").appendChild(userregno);$("uid").innerText = usersList[index].id;$("uname").innerText = usersList[index].name;$("uage").innerText = usersList[index].age;$("ugender").innerText = usersList[index].gender;$("uregno").innerText = usersList[index].regno;}};};xmlHttp.open("get", "javaobjectlists.action?value=" + value, true);xmlHttp.send(null);}</script>  </head>    <body>    输入用户姓名:<input type="text" name="username" id="username" onblur="chkUserInfo(this.value)"/><br />   用户列表:<div id="userinfolist"></div>     </body></html>


~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

测试

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

运行项目

打开浏览器,访问项目index5.jsp页面

输入用户名称

在光标离开时出现用户信息——javaScript获取json数据后怎么解析对象集合的实例

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~



(2)集合中包装复杂类型的数据的传递和解析——以下解析过程和单个对象的解析是一样的,读者可以自己测试

服务器端实体类开发——Address.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

服务器端实体类开发——User.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~


服务器端servlet开发——JavaObjectGroupList.java

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

web.xml配置

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

视图开发——index.jsp

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

测试

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~



                                             
0 0
原创粉丝点击