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

你可能感兴趣的文章
PIL Image对图像进行点乘,加上常数(等像素操作)
查看>>
PIL Image转Pytorch Tensor
查看>>
PIL&QOOT;IOERROR:带有大图像的图像文件被截断(&Q)
查看>>
PIL.Image、cv2的img、bytes相互转换
查看>>
PIL.Image进行图像融合显示(Image.blend)
查看>>
pilicat-dfs 霹雳猫-分布式文件系统
查看>>
Pillow lacks the JPEG 2000 plugin
查看>>
SpringBoot之ElasticsearchRestTemplate常用示例
查看>>
ping 全网段CMD命令
查看>>
ping 命令的七种用法,看完瞬间成大神
查看>>
Pinia入门(快速上手)
查看>>
Pinia:$patch的使用场景
查看>>
Pinia:$subscribe()的使用场景
查看>>
Pinpoint对Kubernetes关键业务模块进行全链路监控
查看>>
Pinterest 大规模缓存集群的架构剖析
查看>>
pintos project (2) Project 1 Thread -Mission 1 Code
查看>>
PinYin4j库的使用
查看>>
PIP
查看>>
pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
查看>>
pip install mysqlclient报错
查看>>