作用:
1) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
2) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
@ResponseBody
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据是其他某种格式的数据时(如json、xml等)使用;
JS端
//请求数据,登录账号 +密码
var data = {
userAccount:username,
userPasswd:password
}
$.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : JSON.stringify(data), //转JSON字符串
dataType: 'json',
contentType:'application/json;charset=UTF-8', //contentType很重要
success : function(result) {
console.log(result);
}
});
Controller处理
@RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json")
@ResponseBody
public Object unlock(@RequestBody User user) {
JSONObject jsonObject = new JSONObject();
try{
Assert.notNull(user.getUserAccount(), "账号为空");
Assert.notNull(user.getUserPasswd(), "密码为空");
User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");
Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "账号错误");
Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "密码错误");
jsonObject.put("message", "成功");
jsonObject.put("status", "success");
}catch(Exception ex){
jsonObject.put("message", ex.getMessage());
jsonObject.put("status", "error");
}
return jsonObject;
}