美文网首页
26.@ResponseBody,@RestController

26.@ResponseBody,@RestController

作者: 若愚同学 | 来源:发表于2018-06-12 22:19 被阅读0次
@ResponseBody

1:废除视图解析器

2:将返回值转换成json格式的字符串

注意:如果没有贴有该注解就直接将对象返回,视图解析器会把@RequestMapping("jsonTestOne")中的值当做路径的一部分拼接上去.

  • 示例代码
@RequestMapping("jsonTestOne")
@ResponseBody
public User jsonTestOne() throws Exception {
    User user = new User(1L,"小林",18,new Date());
    return user;
}
@RestController

是@ResponseBody和@Controller两者的结合,如果类上贴有该注解,那么表示该类所有的方法都以json格式返回

produces

如果出现乱码的情况,那么可以在@RequestMapping中加produces="application/json;charset=utf-8"

  • 示例代码
@RequestMapping(value="jsonTestTwo",produces="application/json;charset=utf-8")
@ResponseBody
public Map<String, Object> jsonTestTwo() throws Exception {
    User user = new User(2L,"小海",18,new Date());
    return user.toJson();
}

相关文章

网友评论

      本文标题:26.@ResponseBody,@RestController

      本文链接:https://www.haomeiwen.com/subject/vhfdeftx.html