
在使用struts 2处理ajax请求并返回json数据时,开发者常会遇到json解析错误或ajax请求进入错误回调函数的问题。这通常源于对struts 2 json插件工作原理的误解。
最初的尝试可能是在Action中手动获取HttpServletResponse的Writer,然后将JSON字符串直接写入响应流,同时在struts.xml中配置result type="json"。例如:
初始Action代码片段(错误示范):
public class PropertyTesting extends ActionSupport {
public String execute() {
JSONObject obj = new JSONObject();
obj.put("Name", "PersonName");
obj.put("ID", "PersonID");
try {
ServletActionContext.getResponse().getWriter().write(obj.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
return SUCCESS;
}
}对应的Struts.xml配置:
<struts>
<constant name="struts.devMode" value="true"/>
<package name="WebTesting" extends="json-default">
<action name="PropertyTesting" class="org.testing.PropertyTesting" >
<result type="json"></result>
</action>
</package>
</struts>这种做法的问题在于:当struts.xml中配置了<result type="json"></result>时,Struts 2的JSON插件会尝试自动序列化Action类中的属性(通常是那些带有公共getter方法的属性)为JSON格式。如果Action中同时手动写入了响应流,就会导致输出冲突或数据格式不符合预期,从而引发前端AJAX的解析错误。JSON插件预期由它自己来控制响应的输出,而不是由Action手动写入。
要正确地从Struts 2 Action返回JSON数据给AJAX请求,关键在于让Struts 2 JSON插件接管JSON的序列化过程。这意味着Action类不应该手动写入响应流,而是应该将需要转换为JSON的数据封装为Action的属性,并通过公共的Getter方法暴露出来。JSON插件会自动检测这些属性并将其序列化。
核心思想:
以下是基于上述原则修正后的Action类和相关配置:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
public class PropertyTesting extends ActionSupport {
// 定义一个Map属性,用于存储需要序列化的数据
private Map<String, String> jsonData;
// 提供公共的Getter方法,JSON插件会通过此方法获取数据
// 注意:方法名通常是 "get" + 属性名首字母大写
public Map<String, String> getJsonData() {
return jsonData;
}
@Override
public String execute() {
// 在execute方法中初始化并填充Map
jsonData = new HashMap<>();
jsonData.put("Name", "PersonName");
jsonData.put("ID", "PersonID");
// 返回SUCCESS,让Struts 2的JSON结果类型处理响应
return SUCCESS;
}
}说明:
前端AJAX代码保持不变,因为它已经正确地设置了dataType:"json",期望接收JSON数据。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta charset="UTF-8">
<title>Property Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
function invokeAjax()
{
$.ajax(
{
type:"POST",
url:"PropertyTesting", // 请求Action的URL
dataType:"json", // 期望接收JSON数据
success: function(responseText)
{
// 成功接收并解析JSON数据
console.log("Success:", responseText);
console.log("Name:", responseText.Name); // 访问JSON数据
console.log("ID:", responseText.ID);
},
error: function(xhr, status, error)
{
// 如果出现错误,这里会打印错误信息
console.log("Error Status:", status);
console.log("Error Message:", error);
console.log("Response Text:", xhr.responseText);
}
});
}
</script>
</head>
<body>
<button type="button" onclick="invokeAjax()" >Submit</button>
</body>
</html>Struts配置也保持不变,因为json-default包和result type="json"是正确使用JSON插件的基础。
<struts>
<constant name="struts.devMode" value="true"/>
<package name="WebTesting" extends="json-default">
<action name="PropertyTesting" class="org.testing.PropertyTesting" >
<result type="json"></result>
</action>
</package>
</struts>重要提示:
通过遵循这些指导原则,你将能够更高效、更稳定地在Struts 2应用中处理AJAX JSON响应。
以上就是Struts 2 AJAX JSON响应处理指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号