Struts2 的问题 异步请求访问Action方法出现bug
[code="java"]
public class EnumConstAction extends BaseAction {
EnumConstService enumConstService;
WEnumConstTab selInfo;// 专门为初始化select 使用
public WEnumConstTab getInfo() {
return info;
}
public void setInfo(WEnumConstTab info) {
this.info = info;
}
public EnumConstService getEnumConstService() {
return enumConstService;
}
public void setEnumConstService(EnumConstService enumConstService) {
this.enumConstService = enumConstService;
}
/**
* 根据父级id和命名空间
* @return
*/
public String findByFatherIdAndNamespace(){
List<WEnumConstTab> list = null;
if (selInfo.getId() != null &&
!"".equals(selInfo.getId())&&
selInfo.getNamespace()!=null
&&!"".equals(selInfo.getNamespace())) {
list = enumConstService.findByFatherIdAndNamespace(selInfo.getId(),selInfo.getNamespace());
} else {
list = new ArrayList<WEnumConstTab>();
}
selInfo = null;
this.getRequest().setAttribute(JSONSTRING, JSONArray.fromObject(list).toString());
return JSON;
}
/**
* 根据命名空间查找
* @return
*/
public String findByNamespace(){
List<WEnumConstTab> list = null;
if (selInfo.getNamespace() != null &&
!"".equals(selInfo.getNamespace())) {
list = enumConstService.findByNamespace(selInfo.getNamespace());
} else {
list = new ArrayList<WEnumConstTab>();
}
selInfo = null;
this.getRequest().setAttribute(JSONSTRING, JSONArray.fromObject(list).toString());
return JSON;
}
//--------------------------------------------------------------------
}
[/code]
当使用Ajax 同时调用 Action 里的 findByNamespace 方法和 findByFatherIdAndNamespace 方法时
方法里的 selInfo 会变成 Ajax 里最后赋值的对象,
[code="java"]
jQuery.post("dnumConstAction_findByNamespace.action",{"selInfo.namespace":"AA"},function(data){});
jQuery.post("dnumConstAction_findByFatherIdAndNamespace.action",
{"selInfo.namespace":"BB","selInfo.id":"11"}},function(data){});
[/code]
结果就会都返回 namespace="BB"的结果
如何解决呢
并发性问题,
[code="java"]
public synchronized void setInfo(WEnumConstTab info) {
this.info = info;
}
[/code]
一般每次请求都会新建一个线程进行处理的吧,selInfo不是共享的变量,按道理是不会出现并发性问题的
[code="java"]public synchronized void setInfo(WEnumConstTab info) {
this.info = info;
} [/code]
另外如果真是并发的问题,这样木有用的,AA调用完set之后执行两个find的时候BB再set一把,还是会有问题的吧
不如在两个find 和setSelInfo函数里都System.out.println一把看看输出值
再不行,就把ajax那个改成同步的, 添加一个参数
$.ajax({
url: "dnumConstAction_findByNamespace.action",
data: {"selInfo.namespace":"AA"},
async:false,
success: function(data){
}
});