【发布时间】:2013-06-08 16:44:06
【问题描述】:
使用 Springs MVC 返回 JSON 数据哪种方式更好,为什么?我应该发回 ResponseEntity 还是只发回 Object?
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public User getDisplayDefault(ModelMap model)
{
return new User("realname", "john smith");
}
对比
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<User> getDisplayDefault(ModelMap model)
{
return new ResponseEntity<User>(new User("realname", "john smith"), HttpStatus.NOT_FOUND);
}
【问题讨论】:
-
您的第一个选项通常会导致 200 OK。这就是你想要的吗?
-
你不需要在第二种情况下使用@ResponseBody。第二种情况在处理异常、设置重定向标头等情况下更好且有用
标签: java web-services spring rest spring-mvc