一、概述
thymeleaf传递bean到springboot控制层,springboot控制层传递bean到thymeleaf页面。
二、Bean对象
public class Demo {
private String name;
private String password;
public Demo() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
三、界面
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<form action="/login" method="post" th:object="${demo}">
name:<input type="text" name="name"/><br/>
password:<input type="text" name="password"/><br/>
<input type="submit"/>
</form>
</body>
</html>
welcome.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<p th:text="${demo.name}"></p>
<p th:text="${demo.password}"></p>
</body>
</html>
四、Controller层
在路径输入“/”,定位到index.html页面。
index.html页面用到${demo},所以需要传递一个Demo对象到index页面,否则会报错。
@Controller("/")
public class DemoController {
/**
* 传递Demo对象到Index页面,Index页面才能提交一个Bean到后台
* @param model
* @return
*/
@RequestMapping("/")
public String index(Model model){
model.addAttribute("demo",new Demo());
return "index";
}
/**
* 把demo传递到welcome页面
* @param demo
* @param model
* @return
*/
@RequestMapping("/login")
public String login(@ModelAttribute(value = "demo") Demo demo, Model model){
model.addAttribute("demo",demo);
return "welcome";
}
}