博客
关于我
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/

你可能感兴趣的文章
Patching Array
查看>>
Spring源码学习(二):Spring容器之prepareContext和BeanFactoryPostProcessor的介绍
查看>>
PatchMatchStereo可能会需要的Rectification
查看>>
Path does not chain with any of the trust anchors
查看>>
Path形状获取字符串型变量数据
查看>>
PAT甲级——1001 A+B Format (20分)
查看>>
Skywalking原理
查看>>
PAT甲级——1006 Sign In and Sign Out (25分)
查看>>
PAT甲级——1007 Maximum Subsequence Sum (25分)
查看>>
PAT甲级——1009 Product of Polynomials (25分)(最后一个测试点段错误)
查看>>
Spring对jdbc的支持
查看>>
vagrant 的安装
查看>>
PayPal网站付款标准版(for PHP)
查看>>
Paystack Android SDK 集成与使用指南
查看>>
pbf格式详解,javascript加载导出pbf文件示例
查看>>
PBOC2.0与3.0的区别
查看>>
PbootCMS entrance.php SQL注入漏洞复现
查看>>
PbootCMS 前台RCE漏洞复现
查看>>
PBT
查看>>
PB级分析型数据库ClickHouse的应用场景和特性
查看>>