restful风格,restcontroller与controller
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
RestController使用的效果是将方法返回的对象直接在浏览器上展示成json格式,而如果单单使用@Controller会报错,需要ResponseBody配合使用。
- 1、如果只是使用@RestController注解Controller类,则方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
例如:本来应该到success.html页面的,则其显示success. - 2、如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
- 3、如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上
@ResponseBody注解。
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("{id}")
@ResponseBody
public User queryUserById(@PathVariable("id")Long id){
return this.userService.queryById(id);
}
@GetMapping("list")
public String all(ModelMap model) {
// 查询用户
List<User> users = this.userService.queryAll();
// 放入模型
model.addAttribute("users", users);
// 返回模板名称(就是classpath:/templates/目录下的html文件名)
return "users";
}
本文详细介绍了如何使用Spring Boot框架中的@RestController和@Controller注解来设计和实现RESTful风格的API。通过对比RestController与Controller的区别,阐述了如何返回JSON、XML等格式的数据,以及如何返回特定的HTML页面。
774

被折叠的 条评论
为什么被折叠?



