JSON(JavaScript Object Notation)一種簡單的資料格式,比xml更輕巧。JSON是JavaScript原生格式,這意味著在JavaScript中處理JSON資料不需要任何特殊的API或工具包。 練習樣本::
首先要建立實體類User.java:
public class User {Integer id;String name;String sex;public User() {super();// TODO Auto-generated constructor stub}public User(Integer id, String name, String sex) {super();this.id = id;this.name = name;this.sex = sex;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}}
json .jsp
<body><table border="1px" align="center"><thead><tr><th>id號</th><th>姓名</th><th>性別</th></tr></thead><tbody id="users"></tbody></table></body>
<script type="text/javascript"><!--window.onload=function(){//擷取xhr對象 var xmlHttp = createXmlHttpRequest(); xmlHttp.onreadystatechange = function() { //判斷 伺服器是否正確返回 相應資訊if (xmlHttp.readyState == 4) {//接受資料 var jsonStr =xmlHttp.responseText; var jsonEmps = eval("("+jsonStr+")"); display(jsonEmps);}} ////規定請求的類型xmlHttp.open("GET", "./ListServlet?timeStamp="+ new Date().getTime(), true);//發送請求xmlHttp.send(null);}function display(obj){var users=document.getElementById("users");for(var i=0;i<obj.length;i++){ //建立tr var tr=document.createElement("tr"); //建立td var td1=document.createElement("td"); var td2=document.createElement("td"); var td3=document.createElement("td"); //添加文本 td1.appendChild(document.createTextNode(obj[i].id)); td2.appendChild(document.createTextNode(obj[i].name)); td3.appendChild(document.createTextNode(obj[i].sex)); //添加到tr中 tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); //添加到users中 users.appendChild(tr); }}function createXmlHttpRequest(){var xmlHttp;try { //Firefox, Opera 8.0+, SafarixmlHttp = new XMLHttpRequest();} catch (e) {try { //Internet ExplorerxmlHttp = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}}}return xmlHttp;}//--></script>
最後是servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");List<User> list=new ArrayList<User>();for(int i=0;i<5;i++){User user=new User(i,"ren"+i,"nv");list.add(user);}String json=JSONArray.fromObject(list).toString();response.setContentType("text/html;charset=UTF-8");PrintWriter out=response.getWriter();out.print(json);System.out.println("as");}