fun

 

JSON学习笔记之一

首先,使用JavaScript的eval()函数实现,将JSON数据串转换成为一个JavaScript对象数组。这里,在Servlet中访问数据库取得记录,并合成JSON串,发送到客户端。

一般,对于企业级应用,使用JavaScript的eval()函数,存在安全隐患问题。这个例子就是感受一下JSON数据串从服务器段被传送到客户端之后,将数据转换成为对象数组或者对象,从而方便地使用JavaScript来实现遍历。

看一下我的Permission实体的Hibernate映射文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="model.xgb.vo.Permission" table="PERMISSION" lazy="false">
    <composite-id>
      <key-property name="id" column="ID" type="integer"/>
      <key-property name="term" column="TERM" type="string"/>
    </composite-id>
    <property name="endDate" column="ENDDATE" type="date"/>
    <property name="start" column="START" type="date"/>
    <many-to-one name="roles" class="model.xgb.vo.Role" lazy="false" unique="true" cascade="save-update">
      <column name="ROLE_ID"/>
    </many-to-one>
    <many-to-one name="org" class="model.xgb.vo.Org" lazy="false" unique="true" cascade="save-update">
      <column name="ORG_ID"/>
    </many-to-one>
    <many-to-one name="operator" class="model.xgb.vo.Operator" lazy="false" unique="true" cascade="save-update">
      <column name="OPERATOR_ID"/>
      <column name="OPERATOR_NAME"/>
      <column name="OPERATOR_TYPE"/>
    </many-to-one>
</class>
</hibernate-mapping>

现在,就是在Servlet中读取对应的记录,然后构造JSON数据,实现的Servlet为GetPermissions,如下所示:

package org.shirdrn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.xgb.bo.ManagerService;
import model.xgb.bo.impl.ManagerServiceImpl;
import model.xgb.vo.Permission;
import cn.edu.cust.levin.BusinessException;
import cn.edu.cust.levin.business.BusinessFactory;

/** author http://www.bt285.cn http://www.5a520.cn
*/

public class GetPermissions extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;

public GetPermissions() {
   super();
}  

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   doPost(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   request.setCharacterEncoding("utf-8");
   response.setCharacterEncoding("utf-8");
   response.setHeader("Cache-Control", "no-cache");
   response.setContentType("text/json;charset=UTF-8");
   String semester = java.net.URLDecoder.decode(request.getParameter("semester"),"UTF-8");
   int orgId = Integer.parseInt(request.getParameter("orgId"));
   PrintWriter out = response.getWriter();
   try {
    ManagerService managerService = (ManagerService)BusinessFactory
     .getBusiness(ManagerServiceImpl.class);
    List permissionList = managerService.getPermissionByOrg(orgId, semester);
    String jsonString = "[";
    for(int i=0;i<permissionList.size();i++) {
     Permission permission = (Permission)permissionList.get(i);
     jsonString += "{";
     jsonString += "\"id\":" + permission.getId() +",";
     jsonString += "\"semester\":\"" + permission.getTerm() +"\",";
     jsonString += "\"startTime\":\"" + permission.getStart().toLocaleString() +"\",";
     jsonString += "\"endTime\":\"" + permission.getEndDate().toLocaleString() +"\",";
     jsonString += "\"orgId\":" + permission.getOrg().getId() +",";
     jsonString += "\"operatorId\":" + permission.getOperator().getId() +",";
     jsonString += "\"operatorName\":\"" + permission.getOperator().getName() +"\",";
     jsonString += "\"roleId\":" + permission.getRoles().getId();
     if(i != permissionList.size()-1) {
      jsonString += "},";
     }
     else {
      jsonString += "}]";
     }
    }
    out.print(jsonString);
    out.flush();
    out.close();
   } catch (BusinessException e) {
    e.printStackTrace();
   }
}          
}

用于显示记录的JSP页面如下所示:

<%@ page language="java" import="java.util.*,model.xgb.vo.*" 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>Get Permissions</title>
<script type="text/javascript" src="js/shirdrnPermission.js"></script>
</head>
<body onLoad="pageLoad();">
<div id="list"></div>
</body>
</html>

我通过使用onLoad事件,加载页面的时候,调用pageLoad()函数,该函数在js/shirdrnPermission.js中实现了,其中js/shirdrnPermission.js的实现如下所示:

var xmlHttp = null;

function pageLoad() {
document.body.style.color = "yellow";
showPermissions();
}

function createXMLHttp() {
if (typeof XMLHttpRequest != "undefined") {
   return new XMLHttpRequest();
} else {
   if (window.ActiveXObject) {
    var aVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
    for (var i = 0; i < aVersions.length; i++) {
     try {
      return new ActiveXObject(aVersions[i]);
     }
     catch (e) {
      alert("error");
     }
    }
   }
}
}

var permissionArray;
var html = null;

function showPermissions() {
html = "<table bgcolor='green' border='1' width='100%'>"
   + "<tr>"
   + "<th>权限ID</th>"
   + "<th>学期</th>"
   + "<th>起始时间</th>"
   + "<th>截止时间</th>"
   + "<th>组织ID</th>"
   + "<th>操作ID</th>"
   + "<th>操作名称</th>"
   + "<th>角色ID</th>"
   + "</tr>";
if(xmlHttp == null) {
   xmlHttp = createXMLHttp();
}
var url = "&semester=" + "2008-2009学年第一学期"
    + "&orgId=" + 1;
xmlHttp.open("GET","getPermissions.servlet?" + encodeURI(encodeURI(url)),true); // GetPermissions在web.xml中配置为<url-pattern>/getPermissions.servlet</url-pattern>
xmlHttp.onreadystatechange = function() {
   if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
    permissionArray = eval("(" + xmlHttp.responseText + ")"); // 将从服务器请求得到的JSON串转换为JavaScript的数组(这里是对象数组)
    for(var i=0;i<permissionArray.length;i++) {
     html += "<tr>";
     html += "<td>" + permissionArray[i].id +"</td>";
     html += "<td>" + permissionArray[i].semester +"</td>";
     html += "<td>" + permissionArray[i].startTime +"</td>";
     html += "<td>" + permissionArray[i].endTime +"</td>";
     html += "<td>" + permissionArray[i].orgId +"</td>";
     html += "<td>" + permissionArray[i].operatorId +"</td>";
     html += "<td>" + permissionArray[i].operatorName +"</td>";
     html += "<td>" + permissionArray[i].roleId +"</td>";
     html += "</tr>";
    }
    html += "</table>";
    var listContainer = document.getElementById("list");
    listContainer.innerHTML = html;
   }
}
xmlHttp.send(null);
}

启动WEB服务器,访问链接http://www.5a520.cn  :8080/xgb/listPermissions.jsp可以看到页面显示的结果,如下所示:

使用JSON进行数据传送,比之于XML自然有很大的优势,至少JSON更加精简,将无关紧要的数据尽量压缩,所以速度比XML要快。

另外,JSON上面的这种使用方式就是使用JavaScript中的eval()函数来实现数据到类型的转换,使用JavaScript的数组或者对象就能遍历数据,而XML还要在JavaScript中使用XML DOM操作。

posted on 2009-04-27 19:07 fun 阅读(1832) 评论(0)  编辑  收藏

导航

统计

常用链接

留言簿(11)

随笔档案

友情链接

搜索

最新评论

阅读排行榜

评论排行榜