博客
关于我
struts2 亲密接触 json(json result type)
阅读量:704 次
发布时间:2019-03-17

本文共 1656 字,大约阅读时间需要 5 分钟。

Struts2 JSONResult 实现详细指南

作为一个开发者,你可能在处理AJAX请求时发现直接使用jsonplugin插件会遇到各种问题。为了更好地解决这个问题,我决定采用Struts2的JSONResult来处理服务器端返回的JSON数据。以下是详细的实现方案和配置步骤。

1. 类实现

我们需要创建一个新的Action类,继承自Result接口,并实现execute方法。以下是完整的实现代码:

public class JSONResult extends Result {
private static final Log log = LogFactory.getLog(JSONResult.class);
public void execute(ActionInvocation invocation) throws Exception {
ActionContext actionContext = invocation.getInvocationContext();
HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
try {
// 获取JSON对象
ValueStack stack = invocation.getStack();
Object jsonObject = stack.findValue("json");
// 序列化为JSON字符串
String json = JSONObject.fromObject(jsonObject).toString();
// 设置响应内容类型
response.setContentType("text/xml;charset=utf-8");
response.getWriter().write(json);
log.debug(json);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw e;
}
}
}

2. Struts配置

struts.xml中添加以下配置:

3. Action类实现

在Action类中添加以下方法:

private Object json;
public Object getJson() {
return json;
}
public void setJson(Object json) {
this.json = json;
}

4. 使用说明

在需要返回JSON数据的Action中,确保json对象已经被正确注入或设置:

public ActionSupport getJsonData() {
json = new JSONObject();
json.put("name", "张三");
json.put("age", 30);
return super.execute();
}

5. 注意事项

  • 如果json的实际类型是String,请确保其符合JSON语法规范。
  • 对于MapList等类型,无需额外处理,可以直接序列化。

通过以上配置,你可以轻松地将Struts2与AJAX请求结合,实现高效的JSON数据交互。这一实现方式简单且高效,能够满足大多数JSON数据交互需求。

转载地址:http://papez.baihongyu.com/

你可能感兴趣的文章
poj 1236(强连通分量分解模板题)
查看>>
poj 1258 Agri-Net
查看>>
quagga 和 zebos
查看>>
poj 1286 Necklace of Beads
查看>>
POJ 1321 棋盘问题
查看>>
poj 1321(回溯)
查看>>
Qt高级——Qt元对象系统源码解析
查看>>
qt调用vs2008编写的dll动态库(隐式调用)
查看>>
Qt读取注册表默认值
查看>>
poj 1679 判断MST是不是唯一的 (次小生成树)
查看>>
POJ 1703 Find them, Catch them
查看>>
POJ 1703 Find them, Catch them 并查集
查看>>
POJ 1738 An old Stone Game(石子合并)
查看>>
POJ 1740 A New Stone Game(博弈)题解
查看>>
Qt网络编程之实例二POST方式
查看>>
POJ 1765 November Rain
查看>>
poj 1860 Currency Exchange
查看>>
POJ 1961 Period
查看>>
POJ 2019 Cornfields (二维RMQ)
查看>>
poj 2057 The Lost House 贪心思想在动态规划上的应用
查看>>