今天在用struts2 异步请求从后台传一个对象到前台时遇到了一个小小的问题,现在此作一个标记,把主要的代码贴上以作备忘。
struts.xml
<action name="getSystemContactorInfo" class="userAction" method="getSystemContactorInfo">
<result type="json">
<param name="includeProperties">systemContactor\.userName,systemContactor\.cellPhone,
systemContactor\.notesMail
</param>
<!-- <param name="includeProperties">systemContactor</param> 这样不对-->
<!-- <param name="includeProperties">systemContactor.*</param> 这样同样不正确-->
</result>
</action>
UserAction
public String getSystemContactorInfo() {
UserModel systemContactor = new UserModel();
systemContactor.setUserName("张三");
systemContactor.setCellPhone("13240151465");
systemContactor.setNotesMail("test@126.com");
return Action.SUCCESS;
}UserModel
public class UserModel{
private String userName;
private String cellPhone;
private String notesMail;
//省略get、set方法
}jsp页面中
$.ajax({
type:'post',
url: 'getSystemContactorInfo.action',
dataType: 'json',
async: true,
success: function showContent(json) {
var userInfo = json.systemContactor;
$("#userName").html(userInfo.userName);
$("#cellPhone").html(userInfo.cellPhone);
$("#notesMail").html(userInfo.notesMail);
}
});<param name="includeProperties">systemContactor</param> 当systemContactor为一个字串或数字时可以这样写<param name="includeProperties">systemContactor.*</param>当systemContactor为list时可这样传
到现在也不是太明白当systemContactor为一个对象时为什么不能直接写在里面,在此标记一下。嗯,有必要去看下官方的api了
文章详细记录了使用Struts2进行异步请求时,将对象从后台传送到前端遇到的问题及解决方法。通过展示具体代码示例,包括struts.xml配置、UserAction类实现及JSP页面的Ajax调用,阐述了如何正确处理对象作为JSON数据传回前端,并在页面上显示。特别指出了在不同场景下如何正确设置参数以避免常见的错误。

1534

被折叠的 条评论
为什么被折叠?



