本文共 1656 字,大约阅读时间需要 5 分钟。
作为一个开发者,你可能在处理AJAX请求时发现直接使用jsonplugin
插件会遇到各种问题。为了更好地解决这个问题,我决定采用Struts2的JSONResult
来处理服务器端返回的JSON数据。以下是详细的实现方案和配置步骤。
我们需要创建一个新的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; } }}
在struts.xml
中添加以下配置:
在Action类中添加以下方法:
private Object json;public Object getJson() { return json;}public void setJson(Object json) { this.json = json;}
在需要返回JSON数据的Action中,确保json
对象已经被正确注入或设置:
public ActionSupport getJsonData() { json = new JSONObject(); json.put("name", "张三"); json.put("age", 30); return super.execute();}
json
的实际类型是String
,请确保其符合JSON语法规范。Map
、List
等类型,无需额外处理,可以直接序列化。通过以上配置,你可以轻松地将Struts2与AJAX请求结合,实现高效的JSON数据交互。这一实现方式简单且高效,能够满足大多数JSON数据交互需求。
转载地址:http://papez.baihongyu.com/