【发布时间】:2015-04-13 08:23:34
【问题描述】:
我想使用 jquery 向我的 struts 操作发送 ajax 发布请求,如下所示:
$.ajax({
type: "POST",
url: "ds/query",
data :JSON.stringify(data),
dataType:"json",
contentType: "application/json; charset=utf-8",
success : function(d, t, x){
console.log(x);
}
});
我的动作配置:
<package name="ds" namespace="/ds" extends="json-default">
<action name="query" class="gov.cbrc.gzbanking.action.DataServiceAction" method="query">
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
<result type="json">
<param name="noCache">true</param>
<param name="excludeNullProperties">true</param>
<param name="root">qRes</param>
</result>
</action>
</package>
我的动作课:
public class DataServiceAction {
private QueryRequest qReq;
private QueryResponse qRes;
public QueryRequest getQr() {
return qReq;
}
public void setQr(QueryRequest qReq) {
this.qReq = qReq;
}
public QueryResponse getqRes() {
return qRes;
}
public void setqRes(QueryResponse qRes) {
this.qRes = qRes;
}
public String query() throws Exception{
App.getLogger().debug(qReq.toString());
String dsClz = SysCodes.getCodeItem("data_service", qReq.getDs()).getConfig1();
Class<?> dsCls = Class.forName(dsClz);
if(!DataService.class.isAssignableFrom(dsCls)){
throw new Exception("specified class does't implement DataService interface.");
}else{
DataService ds = (DataService) dsCls.newInstance();
System.out.println(JsonUtil.toJson(ds.query(qReq)));
qRes = ds.query(qReq);
}
return ActionSupport.SUCCESS;
}
}
QueryRequest 和 QueryResponse 只是 java bean,当我执行我的代码时,服务器可以读取 json 数据并正确完成它的工作,我确信 QueryResponse 对象填充了数据。但我可以'在客户端什么都得不到,responseText 和 responseJson 都是空的。
为什么 struts-json 插件没有自动将我的 QueryResponse 对象转换为 json 字符串?
我的 QueryResponse 类:
public class QueryResponse {
private int total;
private List<?> data;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<?> getData() {
return data;
}
public void setData(List<?> data) {
this.data = data;
}
}
数据列表包含的实际类型必须在运行时确定,例如,如果数据包含角色对象列表: 包 gov.cbrc.gzbanking.domain;
public class Role {
private String id;
private String name;
private String remark;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
那么预期的结果是这样的:
{
total : "1", data :[{"id":"admin", "name":"admin role"}]
}
【问题讨论】:
-
您只使用了一个拦截器来执行您的操作。使用默认堆栈 + json 拦截器。
-
你在使用 Struts 2 JSON 插件吗?
标签: jquery struts2 ognl struts2-json-plugin