SpringBoot+Thymeleaf返回数据还是使用模板如何解决?
@RestController和@Conttroller的区别:
@RestController注解相当于@Controller和@ResponseBody合体的简写。
那同一个controller类中,如何定义哪些方法返回使用模板,哪些直接返回数据呢?
- 类定义上添加@Controller,不能加@RestController;
- 如果想返回模板路径,方法上不能加@ResponseBody注解,如例1;
- 如果想直接返回数据,则在方法上加@ResponseBody注解,如例2
例1:下面的list方法将返回模板路径
@Controller
public class MyController {
...
/**
*使用模板
**/
@GetMapping("/content/list")
String list(Model model) {
ContentDO bContentDO = bContentService.getALL();
model.addAttribute("bContent", bContentDO);
model.addAttribute("gtmModified", DateUtils.format(bContentDO.getGtmModified()));
return "blog/index";
}
}
例2:下面的getContentById方法***添加了@ResponseBody注解***,将直接返回JSON字符串数据,而不通过模板
@ResponseBody
@GetMapping("/content/{cid}")
String getContentById(@PathVariable("cid") Long cid, Model model) {
ContentDO bContentDO = bContentService.get(cid);
model.addAttribute("bContent", bContentDO);
model.addAttribute("gtmModified", DateUtils.format(bContentDO.getGtmModified()));
JSON jsonObject = (JSON) JSONObject.toJSON(bContentDO);
return jsonObject.toJSONString();
}