欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java Servlet生成JSON格式数据并用jQuery显示的方法

程序员文章站 2024-02-06 19:38:22
本文实例讲述了java servlet生成json格式数据并用jquery显示的方法。分享给大家供大家参考,具体如下: 1、servlet通过json-lib生成json...

本文实例讲述了java servlet生成json格式数据并用jquery显示的方法。分享给大家供大家参考,具体如下:

1、servlet通过json-lib生成json格式的数据

import java.io.ioexception;
import java.io.printwriter;
import java.util.*;
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 json.person;
import net.sf.json.jsonarray;
import net.sf.json.jsonobject;
@webservlet("/jsonservlet")
public class jsonservlet extends httpservlet {
public jsonservlet() {
super();
}
public void destroy() {
super.destroy(); // just puts "destroy" string in log
// put your code here
}
public void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
response.setcontenttype("application/x-json");
response.setcharacterencoding("gbk");
printwriter out = response.getwriter();
arraylist<person> items=new arraylist<person>();
items.add(new person(2,"jack"));
items.add(new person(2,"bob"));
items.add(new person(2,"alex"));
jsonarray jsonarray=new jsonarray();
jsonarray.addall(items);
out.print(jsonarray.tostring());
}
public void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
doget(request,response);
}
public void init() throws servletexception {
// put your code here
}
}

2、前端页面代码

<%@ page language="java" contenttype="text/html; charset=iso-8859-1"
pageencoding="iso-8859-1"%>
<!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=iso-8859-1">
<title>insert title here</title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(
function() {
$("#kick").click(
function() {
$.ajax({
type : "post",//post方法
url : "jsonservlet",
data : {
"legs" : "2",
"name" : "aa"
},
//ajax成功的回调函数
success : function(returndata) {
var arr = eval(returndata);
$.each(arr, function(index, content) {
$("#result").append(
"<div>" + content.legs
+ "</div>" + "<div>"
+ content.name
+ "</div><hr/>");
});
}
});
});
});
</script>
</head>
<body>
<input type="button" id="kick" value="kick">
<div id="result"></div>
</body>
</html>

jquery也可以用.getjson实现异步数据获取

<script type="text/javascript">
$(document).ready(
function() {
$("#kick").click(function() {
$.getjson("jsonservlet",function(returndata){
var arr = eval(returndata);
$("#result").html("");//清空info内容
$.each(arr, function(index, content) {
$("#result").append(
"<div>" + content.legs
+ "</div>" + "<div>"
+ content.name
+ "</div><hr/>");
});
});
});
});
</script>

希望本文所述对大家jsp程序设计有所帮助。