通常,我们会从servlet返回一个集合或者对象的数据给jsp显示,此时就可以使用一些包将集合、数组、对象转为json类型的数据发给前端,前端再进行方法处理后显示,比较难的是json的遍历,我研究了好久。。。。。。下面我写了一个小小的例子。
User对象:
package cn.sdut.ajaxdemo;
public class User {
int id;
String name;
int age;
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
servlet代码:
package cn.sdut.ajaxdemo;
import java.io.IOException;
import java.util.ArrayList;
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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@WebServlet("/AjaxDemo_json")
public class AjaxDemo_json extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* 要想实现JSON和java对象之间的互转,需要借助第三方jar包,这里使用json-lib这个jar包,
* json-lib需要commons-beanutils-1.8.0.jar、
* commons-collections-3.2.1.jar、
* commons-lang-2.5.jar、
* commons-logging-1.1.1.jar、
* ezmorph-1.0.6.jar五个包的支持,可能在我的资源里有,大家可以去下载。
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
User u= new User(3,"ghjbj",3);
JSONObject json = JSONObject.fromObject(u);
System.out.println(json);
response.getWriter().write(json.toString());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
List<User> list = new ArrayList<>();
list.add(new User(1,"zxc",1));
list.add(new User(2,"dnn",2));
JSONArray json = JSONArray.fromObject(list);
System.out.println(json.toString());
response.getWriter().write(json.toString());
}
}
jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>简易ajax 返回类型json</title>
</head>
<input type="button" οnclick="ajaxGETMethod();" value="ajax1点击"><div id="ajax1">11xml</div>
<input type="button" οnclick="ajaxPOSTMethod();" value="ajax2点击"><div id="ajax2">22xml</div>
</body>
<script type="text/javascript">
function ajaxGETMethod(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200){
//返回值格式 {"age":1,"id":1,"name":"zxc"} 注意 不是{fname:"John",lname:"Doe",age:25}这种格式
var json = eval('('+xmlhttp.responseText+')');
for(var x in json ){
alert(json[x]);
}
document.getElementById("ajax1").innerHTML =json.id+json.name+json.age;
}
}
xmlhttp.open("get","${pageContext.request.contextPath}/AjaxDemo_json?"+Date().getTime(),true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
<script type="text/javascript">
function ajaxPOSTMethod(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200){
//返回值格式 : [{"age":1,"id":1,"name":"zxc"},{"age":2,"id":2,"name":"dnn"}]
var json = eval('('+xmlhttp.responseText+')');
for(var i in json){
document.getElementById("ajax2").innerHTML +=json[i].id+" "+json[i].name+" "+json[i].age+"<br>";
}
}
}
xmlhttp.open("POST","${pageContext.request.contextPath}/AjaxDemo_json?"+Date(),true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
</html>