ajax 返回map獲取不到 拋出HttpMessageNotWritableException
Controller返回String數據,ajax可以正常接收,但是返回對象時(我是map類型),就一直是error。
如果瀏覽器打開F12查看網絡訪問,ajax執行時,Controller的類執行正常,但是返回的map類型數據,ajax獲取不到,並拋出異常:HttpMessageNotWritableException
。
ajax代碼:
jQuery.ajax({
type: "POST",
url: "updateCustomerMobile.dhtml",
data: "mobile="+newMobile,
async: false,
success: function (msg) {
alert("成功");
},
error: function(){
alert("失敗");
}
});
Controller代碼:
@ResponseBody
@RequestMapping("/updateCustomerMobile.dhtml")
public Map<String, String> updateMoblie(String mobile){
Map<String, String> map = new HashMap<>();
...
return map;
}
結果ajax死活彈出"失敗",搞得我快崩潰了。
解決方案:
- SpringMVC的配置:加上
<mvc:annotation-driven />
註解掃描 - 在pom.xml中加入這兩個註解驅動:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
問題解決,網上的回答亂七八糟的,我在此記錄一下,方便大家解決問題。
真的是,阿西吧~