不要使用@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;
}