今天写代码的时候忽然发生了这样一个问题,在我编写后台数据接口的时候,后台的返回值前端 Ajax
无法获取,请教同事,又没能得到我想要的结果,所以想记录一下这个简单的错误,也算是给自己敲个警钟。错误代码如下:
@RequestMapping("/delGlobeLayerData.do")
@ResponseBody
public Object delGlobeLayerData(String uuid){
int result = service.deleteByPrimaryKey(uuid);
if (result > 0) {
return new HashMap<String, String>().put("result", "SUCCESS");
}
return null;
}
当喝了口水,静下心来看这段代码的时候,发现了错误的原因:及当删除操作成功之后 result > 0
肯定是为 true
的,但是由于将代码简化,导致我忽略了判断条件中 return
的其实是 put
的返回值而非 HashMap
对象。同时 恰巧delGlobeLayerData
函数的返回值被定义为 Object
类型,故让这个问题在写代码的时候不容易被发现。所以正确的代码如下:
@RequestMapping("/delGlobeLayerData.do")
@ResponseBody
public Object delGlobeLayerData(String uuid){
Map<String, String> obj = new HashMap<String, String>();
int result = service.deleteByPrimaryKey(uuid);
if (result > 0) {
obj.put("result", "SUCCESS");
}
return obj;
}
问题解决了,带着好奇心还是去看了下 HashMap
的源码
public V put(K paramK, V paramV) {
if (this.table == EMPTY_TABLE)
inflateTable(this.threshold);
if (paramK == null)
return putForNullKey(paramV);
int i = hash(paramK);
int j = indexFor(i, this.table.length);
for (Entry localEntry = this.table[j]; localEntry != null; localEntry = localEntry.next) {
Object localObject1;
if ((localEntry.hash != i) || (((localObject1 = localEntry.key) != paramK) && (!(paramK.equals(localObject1)))))
continue;
Object localObject2 = localEntry.value;
localEntry.value = paramV;
localEntry.recordAccess(this);
return localObject2;
}
this.modCount += 1;
addEntry(i, paramK, paramV, j);
return null;
}
从以上代码可以看出 put
函数的返回值虽然定义为泛型对象,但实际上返回值为 null
。