1.json是一种优秀的数据格式,在移动开发和web开发中经常用到,本例中通过一个小案例讲解如何通过alibaba的开源框架fastjson来解析jason数据格式并通过js实现无跳转刷新
2,新建一个web项目,这是我的项目:我这里直接用servlet写的
注意导包,我这里到了很多无用的包,其实主要的包是下面几个:
这个三个包是必须的,其他都是开发基本web的常用包
3.创建一个domain:
package com.keson.domain;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("employee")
public class Employee {
@XStreamAlias("no")
private Integer no;
@XStreamAlias("name")
private String name;
@XStreamAlias("age")
private Integer age;
@XStreamAlias("gender")
private String gender;
@XStreamAlias("job")
private String job;
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
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;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
注意:这里的domain必须用@XStreamAlias("employee")注解,以便把domain转成json数据格式,属性名字最好和注解里面的标识名字一样
3,.这是一个servlet:
public class JsonServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Employee employee =new Employee();
employee=getEmployee();
XStream xStream = new XStream(new DomDriver());
xStream.autodetectAnnotations(true);
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/json; charset=utf-8");
PrintWriter writer = response.getWriter();
String jsonResult = JSON.toJSONString(employee, false);
System.out.println(jsonResult);
writer.write(jsonResult);
writer.close();
}
public static Employee getEmployee(){
Employee employee=new Employee();
employee.setNo(1);
employee.setName("keson");
employee.setAge(20);
employee.setGender("M");
employee.setJob("软件工程师");
return employee;
}
}
这里的数据我是通过伪造的,当然如果有数据库的话可以通过jdbc或其他持久层框架来实现,这里只是举例,所以数据伪造简便些
标红色的部分是怎样通过java代码把对象转成json数据的,这个基本上是可以套用的
4.jsp页面:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript">
var root_path = "${pageContext.request.contextPath}";
</script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/show.js"></script>
</head>
<body>
<table border="1px">
<tr>
<td>no</td>
<td>name</td>
<td>age</td>
<td>gender</td>
<td>job</td>
</tr>
<tr>
<td><input type="text" id="no_id"></td>
<td><input type="text" id="name_id"></td>
<td><input type="text" id="age_id"></td>
<td><input type="text" id="gender_id"></td>
<td><input type="text" id="job_id"></td>
</tr>
<tr><td colspan="5"><input type="button" value="提交" onclick="submitBtn()"></td></tr>
</table>
</body>
</html>
这里的jsp页面非常简单也很简洁,我是通过js去实现数据交互的,所以在jsp页面中没有写任何js的代码
5.js代码:
function submitBtn() {
reqeustDetail();
}
function createXMLHttpRequest() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlHttp = null;
window.alert("Cannot support XMLHttpRequest");
}
return xmlHttp;
}
function reqeustDetail() {
var xmlHttp = createXMLHttpRequest();
var url =root_path+"/json";
if (xmlHttp) {
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
parseMessage(xmlHttp);
} else {
window.alert("Error number: " + xmlHttp.status
+ ", error describe: " + xmlHttp.statusText);
}
}
};
xmlHttp.send(null);
}
}
function parseMessage(xmlHttp) {
var jsondoc = xmlHttp.response;
// var obj = eval('('+jsondoc+')');
var obj=Function("return"+jsondoc)();
var no_id=document.getElementById("no_id");
var name_id=document.getElementById("name_id");
var age_id=document.getElementById("age_id");
var gender_id=document.getElementById("gender_id");
var job_id=document.getElementById("job_id");
no_id.value=obj.no;
name_id.value=obj.name;
age_id.value=obj.age;
gender_id.value=obj.gender;
job_id.value=obj.job;
}
这里是通过ajax实现异步请求,通过js的document.getElementById来获取及赋值的,其实ajax部分基本上是套用,标有颜色的部分才是去实现逻辑的,标黄色部分是怎样通过js去解析json的,非常的简便
6,测试
这是原始的页面效果:
当点击提交时页面会无跳转刷新,可以观察到URL没有什么变化,最后的结果就是把数据带过来了,而且响应是非常快的,在数据量大的情况下效果可能更加明显,结果如下图: