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[i].getField(), objs[i - 1]);
}
} else{
for(; i< columns.length;i++){
rowObj.element(columns[i].getField(), objs[i]);
}
}
if(idColumnName != null && !idColumnName.isEmpty()){
rowObj.element(idColumnName, objs[objs.length -1]);
}
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[i].getField(), objs[i - 1]);
}
} else{
for(; i< columns.length;i++){
rowObj.element(columns[i].getField(), objs[i]);
}
}
if(idColumnName != null && !idColumnName.isEmpty()){
if(colorColumnName != null){
rowObj.element(idColumnName, objs[objs.length -2]);
rowObj.element(colorColumnName, objs[objs.length -1]);
}
else{
rowObj.element(idColumnName, objs[objs.length -1]);
}
}
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();
}
}
sturts 配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="getgps" namespace="" extends="default">
<!-- 网点地图获取经纬度 -->
<action name="queryMapAction" class="stationMapQueryBean" method="sationMapQuery">
</action>
<action name="initMapQueryAction" class="stationMapQueryBean" method="initMapQuery">
<param name="selcetedIdString">${selcetedIdString}</param>
<result >
/npmap/statiomMap.jsp
</result>
</action>
<action name="initAction" class="stationMapQueryBean" method="init">
<result >
/npmap/stationMapQueryList.jsp
</result>
</action>
</package>
</struts>
2)自己定义个结构类型,实现Result
<package name="kingee_ast_default" namespace="/mobile" extends="struts-default" >
<result-types>
<result-type name="json" class="JSONResult"/>
</result-types>
<action name="queryCtyTwn" class="mobileQueryCtyTwn" method="getCityTown">
<result type="json"></result>
</action>
</package>
/**
* zjpost
*/
package com.zjpost.npmis.struts2;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
/***
* @author <a href="[email protected]">XXX</a>
* @version $Id: $
*/
public class MobileBaseResult implements Result {
@Override
public void execute(ActionInvocation arg0) throws Exception {
}
}
/**
* zjpost
*/
package com.zjpost.npmis.action.mobile;
import java.io.IOException;
import com.opensymphony.xwork2.ActionSupport;
import com.zjpost.npmis.service.mobile.IBusinesSiteServer;
import com.zjpost.rural.model.management.User;
import com.zjpost.rural.util.JsonUtil;
/***
* @author <a href="[email protected]">XXX</a>
* @version $Id: $
*/
public class BusinesSiteAction extends ActionSupport{
private IBusinesSiteServer businesSiteServer;
// private User usr;
public String getCityTown(){
// businesSiteServer.queryCtiyOrTown(usr, null);
String temp = "{" +
" \"posts\" : [{ \"usr_id\": \"1000010012342\"}]} ";
try {
JsonUtil.sendJsonString(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
public IBusinesSiteServer getBusinesSiteServer() {
return businesSiteServer;
}
public void setBusinesSiteServer(IBusinesSiteServer businesSiteServer) {
this.businesSiteServer = businesSiteServer;
}
}