次のjarファイルを各サイトからダウンロード
・ commons-beanutils-1.7.0.jar
・ commons-collections-3.1.jar
・ commons-lang-2.0.jar
・ commons-logging-1.1.1.jar
・ ezmorph-1.0.6.jar
・ json-lib-2.3-jdk15.jar
次のjavascriptファイルをダウンロード
・ json2.js
package sample; public class SampleBean { private String empNo; private String empNm; private String deptCd; private String deptNm; public SampleBean(String empNo, String empNm, String deptCd, String deptNm) { this.empNo = empNo; this.empNm = empNm; this.deptCd = deptCd; this.deptNm = deptNm; } public String getEmpNo() { return empNo; } public String getEmpNm() { return empNm; } public String getDeptCd() { return deptCd; } public String getDeptNm() { return deptNm; } }
package sample; import java.io.IOException; import java.util.ArrayList; import java.util.List; 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 SampleServlet extends HttpServlet { private static final long serialVersionUID = 2566404457396898077L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json; charset=UTF-8"); response.setHeader("Cache-Control", "private"); List result = new ArrayList(); for(int i = 1; i <= 1000; i++) { String renban = String.format("%1$04d", i); SampleBean sBean = new SampleBean( "EMP" + renban, "従業員氏名" + renban, "DPT" + renban, "所属部門名" + renban ); result.add(sBean); } JSONArray json = JSONArray .fromObject(result); response.getOutputStream().write(json.toString().getBytes("UTF-8")); } }
function getEmpList() { var xmlResult = new XMLHttpRequest(); xmlResult.open("POST", "http://localhost:8080/JSONSampleProject/SampleServlet", true); xmlResult.onreadystatechange = function() { if (xmlResult.readyState == 4) { var jsonResult = JSON.parse(xmlResult.responseText); var jugyoinList = "
empNo | \n" + "\t\tempNm | \n" + "\t\tdeptCd | \n" + "\t\tdeptNm | \n" + "\t
---|---|---|---|
" + jsonResult[i].empNo + " | \n" + "\t\t" + jsonResult[i].empNm + " | \n" + "\t\t" + jsonResult[i].deptCd + " | \n" + "\t\t" + jsonResult[i].deptNm + " | \n" + "\t
<!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>JSONサンプル</title> <script type="text/javascript" src="script/json2.js"></script> <script type="text/javascript" src="script/Sample.js"></script> </head> <body> <input type="button" onclick="javascript:getEmpList()" name="search" value="検索"><br /> <br /> <div id="jugyoinList" style="width:500px"></div> </body> </html>