chinadeng 发表于 2013-1-29 10:32:08

ssh 架构下 json 数据的产生概述

N没写博客了,也是来****公司后的第一博。呵呵
  今天绝大多数的Web  开发会涉及到ajax json。先从前台开始说起(基于Jquery)
(1) web 前台产生异步请求;jquery 比较常用的两个函数:
 1) 
 
  $.ajax({
    type:"post",
    url: addURL,
    dataType: "json",
    data:param,
      success: function (data){
       alert("dd"); 
   alert(data);
     
   }
    });
   其中addURL 处理该请求的后台Action,param表示请求的参数,是以键值对的显示出现,如:
 
   var  selcetedIdString =  "${param.selcetedIdString}";
    var  addURL = '${addURL}';
    var  param = {selcetedIdString:selcetedIdString};
2)第二种方法,利用jqurey 提供的函数

       $.getJSON(url,param,function(data){
        alert(data);
        });
参数意义与第一种一样,两者的唯一区别在于 返回的data 的类型,第一种是是返回对象不是json对象,要进过
eval 函数转化才能成json对象,第二种,返回的data直接是json数据。
前台大致情况是这样的,后台是 json数据的来源,下面来描述后台怎么样常识json 数据,基于ssh 开发,struts2 很好的集成了 对json 数据产生支持,利用struts2 产生json 数据,需要用到包为:
  json-lib-2.4-jdk15.jar;ezmorph-1.0.2.jar等。主要是利用import net.sf.json.*下的静态类,写入到请求里。其中主要的注意点,Action 里,请求处理成功后,是否有配置Result;
  1) Action 返回的是Void 
    Action中 
    public void sationMapQuery(){
Helper.logEntrance("sationMapQuery");

try {
Helper.checkNotNull("sationMapQuery_selcetedIdString", selcetedIdString, "sationMapQuery_selcetedIdString");
String idtemp = selcetedIdString;
selcetedId = null;
selcetedId =  new ArrayList<Long>();
if(idtemp.contains(",")){
String arrayID [] = idtemp.split(",");
for(String id:arrayID){
selcetedId.add(new Long(id));
}
}else {
selcetedId.add(new Long(idtemp));
}
List selectedList  = stationMapServer.queryByIDs(selcetedId);
String listjson = JsonUtil.getListToJsonData(selectedList);
System.out.println(listjson);
JsonUtil.sendJsonString(listjson);
} catch (IOException e) {
e.printStackTrace();

}

/*JSONObject jsonObject=new JSONObject();
try {
JsonUtil.sendCallbackMessage("true");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonObject.element("isSuccess", true);*/
Helper.logExit("sationMapQuery");

}
其中package com.zjpost.rural.util;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletResponse;
 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
 
import org.apache.struts2.ServletActionContext;
 
 
import com.zjpost.rural.model.intermedia.JsonColumn;
import com.zjpost.rural.model.intermedia.JsonTreeItem;
 
public class JsonUtil {

public static void sendJsonString(String content)throws IOException{      
if(content == null){
content = "";
}
        HttpServletResponse response = ServletActionContext.getResponse();      
        response.setCharacterEncoding("UTF-8");      
        response.setContentType("text/plain");
        response.getWriter().write(content);  
}
//message values:
// success : "true"
// error: "detail error message like : db connection exception"
// forword: "forword"
public static void sendCallbackMessage(String message) throws IOException{
JSONObject jsonMessage = new JSONObject();
jsonMessage.element("message", message);
HttpServletResponse response = ServletActionContext.getResponse();      
        response.setCharacterEncoding("UTF-8");      
        response.setContentType("text/plain");
        response.getWriter().write(jsonMessage.toString()); 
}
public static void sendHtmlCallbackMessage(String message) throws IOException{
JSONObject jsonMessage = new JSONObject();
jsonMessage.element("message", message);
HttpServletResponse response = ServletActionContext.getResponse();      
        response.setCharacterEncoding("UTF-8");      
        response.setContentType("text/html");
        response.getWriter().write(jsonMessage.toString()); 
}
public static String toJsonTable(JsonColumn[] columns, List<Object[]> rows, Long total){

return toJsonTable(columns, rows, total, null, false);
}


public static String toJsonTable(JsonColumn[] columns, List<Object[]> rows, Long total, String idColumnName,boolean needCheckbox){
JSONObject table = new JSONObject();
table.element("total", total);
table.element("columns", columns);
JSONArray rowArray = new JSONArray();
if(rows != null && rows.size() > 0){
for(Object[] objs: rows)
{
JSONObject  rowObj = new JSONObject();
int i=0;
if (needCheckbox) {
i = 1;
for (; i < columns.length ; i++) {
rowObj.element(columns.getField(), objs);
}
} else{
for(; i< columns.length;i++){
rowObj.element(columns.getField(), objs);
}
}
if(idColumnName != null && !idColumnName.isEmpty()){
rowObj.element(idColumnName, objs);
}
rowArray.add(rowObj);
}
}
table.element("rows", rowArray);
return table.toString();
}

public static String toJsonTableWithColor(JsonColumn[] columns, List<Object[]> rows, Long total, String idColumnName,boolean needCheckbox,String colorColumnName){
JSONObject table = new JSONObject();
table.element("total", total);
table.element("columns", columns);
JSONArray rowArray = new JSONArray();
if(rows != null && rows.size() > 0){
for(Object[] objs: rows)
{
JSONObject  rowObj = new JSONObject();
int i=0;
if (needCheckbox) {
i = 1;
for (; i < columns.length ; i++) {
rowObj.element(columns.getField(), objs);
}
} else{
for(; i< columns.length;i++){
rowObj.element(columns.getField(), objs);
}
}
if(idColumnName != null && !idColumnName.isEmpty()){
if(colorColumnName != null){
rowObj.element(idColumnName, objs);
rowObj.element(colorColumnName, objs);

}
else{
rowObj.element(idColumnName, objs);
}
}

rowArray.add(rowObj);
}
}
table.element("rows", rowArray);
return table.toString();
}
public static String toJsonTable(JsonColumn[] columns, List<Object[]> rows, Long total, String idColumnName){
return toJsonTable(columns, rows, total, idColumnName, true);
}
 
public static List<JsonTreeItem> makeTree(List<JsonTreeItem> items)
{
Map<Long, List<JsonTreeItem>> parentMap = new HashMap<Long, List<JsonTreeItem>>();
List<JsonTreeItem> rootItems = null;
if(items != null && items.size() >0){
for(JsonTreeItem item : items){
if(parentMap.containsKey(item.getParentId())){
parentMap.get(item.getParentId()).add(item);
}
else{
List<JsonTreeItem> children = new  ArrayList<JsonTreeItem>();
children.add(item);
parentMap.put(item.getParentId(), children);
}
}
rootItems = parentMap.get(0L);
if(rootItems != null && rootItems.size() > 0){
for(JsonTreeItem rootItem : rootItems){
setChildrenItem(rootItem, parentMap);
}
}
}
changeParentCheckStatus(rootItems);
return rootItems;
}
public static void changeParentCheckStatus(List<JsonTreeItem> items){

for(JsonTreeItem item : items){
if(item.getChildren().size() > 0)
{
item.setChecked(false);
changeParentCheckStatus(item.getChildren());
}
}
}
//递归set children
public static void setChildrenItem(JsonTreeItem parentItem, Map<Long, List<JsonTreeItem>> itemMap){
List<JsonTreeItem> children = null;
if(itemMap.containsKey(parentItem.getId())){
children  = itemMap.get(parentItem.getId());
for(JsonTreeItem item : children){
setChildrenItem(item, itemMap);
}
parentItem.setChildren(children);
}
}
public static String getListToJsonData(List<?> dataList) {
JSONArray jsonArray = null;
try{
jsonArray = JSONArray.fromObject(dataList);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return jsonArray.toString();


}

}
<div style="text-align: left;">
页: [1]
查看完整版本: ssh 架构下 json 数据的产生概述