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

你可能感兴趣的文章
pprint 排序字典但不是集合?
查看>>
pptp拨号上网
查看>>
ppt上的倒计时小工具_PPT中有哪些「看似很 LOW,实则惊艳」的小工具
查看>>
PPT添加视频的路径问题
查看>>
PPT美化插件 islide 安装过程问题“加载com加载项时运行出现错误”
查看>>
Prefix Tuning:详细解读Optimizing Continuous Prompts for Generation
查看>>
PreparedStatement 与Statement 的区别,以及为什么推荐使用 PreparedStatement ?
查看>>
PreparedStatement 查询 In 语句 setArray 等介绍。
查看>>
presentModalViewController显示半透明的一个view
查看>>
PresentViewController切换界面
查看>>
PyTorch之torch.utils.data.DataLoader解读
查看>>
PyTorch之DataLoader杂谈
查看>>
presto、druid、sparkSQL、kylin的对比分析
查看>>
Presto分布式大数据查询引擎
查看>>
Presto架构及原理
查看>>
Presto(一)集群部署
查看>>
Presto(二)开启安全认证
查看>>
Pricing procedure Steps and Details in SAP MM (from SCN)
查看>>
Prim 算法在不同权重范围内的性能分析及其实现
查看>>
Primace 5.0软件与KEIL单片机软件联合在线仿真步骤
查看>>