JSON是Javascript Object Notation, 它是一种轻量级的数据结构。由于具有易于阅读,易于机器解析的特点,它非常适合于作为数据传输的格式,特别是对于客户端使用Javascript来解析的Web应用。
AJAX应用实现大体上分为服务端和客户端两部门,客户端若使用prototype的js库,能非常简单地实现AJAX请求和响应的获取。prototype中的Form.serialize方法更能将表单中的所有字段序列化,作为发送给服务端的数据异步发送。在服务端,需要有一定的机制来返回稳定格式的报文给客户端,并且这个响应的格式必须是易于客户端来解析的,JSON格式的报文是不错的选择。
在这里,我实现了一个基于JSON的服务端响应类,以满足上述的需求,服务端代码如下:
package cn.ih.util.web;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
/** *//**
*
* @author ih
*
*/
public class JsonResponseUtils ...{
private static final String NODE_RESULT="result";
private static final String NODE_MESSAGE="message";
private static final String NODE_REASON="reason";
private static final String NODE_EXTRA_CONTENT="extraContent";
public static final String REASON_UNLOGON="unlogon";
public static final String REASON_ACCESS_DENY="accessDeny";
public static final String REASON_BIZ_CONSTRAINT="bizConstraint";
public static final String REASON_EXCEPTION="error";
/** *//**
* 通过response返回到客户端
* @param response
* @param responseContent
* @throws Exception
*/
public static void outputResponse(HttpServletResponse response,String responseContent)throws Exception...{
response.getWriter().write(responseContent);
}
/** *//**
* 返回json格式的报文
* @param result
* @param message
* @param reason
* @param customerizedContent
* @return
*/
@SuppressWarnings("unchecked")
public static String generateResponse(boolean result,String message,String reason,Map customerizedContent)...{
Map map=new LinkedHashMap();
map.put(NODE_RESULT,result);
if(StringUtils.isNotEmpty(message))
map.put(NODE_MESSAGE, message);
if(StringUtils.isNotEmpty(reason))
map.put(NODE_REASON,reason);
if(customerizedContent!=null)
map.put(NODE_EXTRA_CONTENT, customerizedContent);
return generateJsonObjectString(map);
}
/** *//**
* 返回处理成功的报文
* @return
*/
public static String generateSuccessResponse()...{
return generateResponse(true, null, null, null);
}
/** *//**
* 返回处理成功的报文,含成功提示信息和用户自定义内容
* @param message
* @param customerizedContent
* @return
*/
@SuppressWarnings("unchecked")
public static String generateSuccessResponse(String message,Map customerizedContent)...{
return generateResponse(true, message, null, customerizedContent);
}
/** *//**
* 返回处理成功的报文,含成功提示信息
* @param message
* @return
*/
public static String generateSuccessResponse(String message)...{
return generateResponse(true, message, null, null);
}
/** *//**
* 返回处理失败的报文, 原因为未登陆
* @param message
* @return
*/
public static String generateUnlogonResponse(String message)...{
return generateResponse(false, message, REASON_UNLOGON, null);
}
/** *//**
* 返回处理失败的报文, 原因为无权限

