效果图如下:
1.创建student类
package com.neusoft.json.domain;
public class Student {
private String name;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Student(String name, double salary) {
this.name = name;
this.salary = salary;
}
}
2.创建servlet
package com.neusoft.json.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 com.neusoft.json.domain.Student;
import flexjson.JSONSerializer;
@WebServlet("/show")
public class SSS extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Student> ss=new ArrayList<>();
ss.add(new Student("nihao", 250));
ss.add(new Student("张三" ,550));
ss.add(new Student("lisi",1250));
JSONSerializer js=new JSONSerializer();
String str=js.exclude("class").serialize(ss);
response.getWriter().println(str);
}
}
3.创建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">
<script type="text/javascript">
var q;
function yq(){
if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
}
function s(){
q=yq();
q.onreadystatechange=function(){
if(q.readyState==4){//请求状态
if(q.status==200){//http状态
var t=q.responseText;
var json=eval("("+t+")");
var table="<table border='1' width='70%'><tr><th>姓名</th><th>工资</th></tr>";
for(i=0;i<json.length;i++){
table+="<tr><td>"+json[i].name+"</td><td>"+json[i].salary+"</td></tr>";
}
table+="</table>";
var div=document.getElementById("div");
div.innerHTML=table;
}
}
}
q.open("GET","${pageContext.request.contextPath}/show");
q.send(null);
}
</script>
<title>Insert title here</title>
</head>
<body>
<input type="button" value="显示" onclick="s()" />
<div id="div"></div>
</body>
</html>