9. Spring Boot Pages
9.1. 理解 Pages
9.3. 页面获取数据
Model, ModelMap, and ModelAndView are used to define a model in a Spring MVC application.
- Model defines a holder for model attributes and is primarily designed for adding attributes to the model.
- ModelMap is an extension of Model with the ability to store attributes in a map and chain method calls.
- ModelAndView is a holder for a model and a view; it allows to return both model and view in one return value.
9.3.1. Model
| @GetMapping("/")
public String homePage(Model model) {
model.addAttribute("appName", appName);
return "home";
}
|
页面上:
<span th:text="${appName}">Our App</span>
9.3.2. ModelMap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | @GetMapping("/getMessageAndTime")
public String getMessageAndTime(ModelMap map) {
var ldt = LocalDateTime.now();
var fmt = DateTimeFormatter.ofLocalizedDateTime(
FormatStyle.MEDIUM);
fmt.withLocale(new Locale("sk", "SK"));
fmt.withZone(ZoneId.of("CET"));
var time = fmt.format(ldt);
map.addAttribute("message", message).addAttribute("time", time);
return "show";
}
|
9.3.3. ModelAndView
| @GetMapping("/getMessage2")
public ModelAndView getMessage() {
var mav = new ModelAndView();
mav.addObject("message", message);
mav.setViewName("show");
return mav;
}
|
9.3.4. @ModelAttribute
| @ModelAttribute("motd")
public String message() {
return messageService.getMessage();
}
|