SpringBoot搭配Thymeleaf只能返回文本數據,不訪問模板頁面問題


不要使用@RestController註解,@RestController註解是@ResponseBody和@Controller的集合體,使用@RestController(以及@ResponseBody)註解會默認返回數據,而不會請求到頁面。
下面代碼要使用到 Thymeleaf 在 list/index.html 這個模板,所以這裏只用 @Controller !

@Controller
public class NewsController {...}
1
2
@GetMapping("list/all")
public String listAll(Model model) {
    List<News> list = mNewsService.selectAll();
    model.addAttribute("newsList", list);
    return "list/index";
}
1
2
3
4
5
6
如果有需要直接返回的數據,那麼在方法上加@ResponseBody即可。
下面這段代碼直接返回 list 數據到頁面上,不會用到 Thymeleaf 模板。

@GetMapping("list/all")
@ResponseBody
public List<News> listAll() {
    List<News> list = mNewsService.selectAll();
    return list;
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章