首先,pom.xml中导入thymeleaf的依赖:
org.springframework.boot spring-boot-starter-thymeleaf
application.yml配置
#ThymeLeaf配置
thymeleaf:
#模板的模式,支持 HTML, XML TEXT JAVAscript
mode: HTML5
#编码 可不用配置
encoding: UTF-8
#内容类别,可不用配置
content-type: text/html
#开发配置为false,避免修改模板还要重启服务器
cache: false
#配置模板路径,默认是templates,可以不用配置
prefix: classpath:/templates/
# 后缀
suffix: .html
User代码
import lombok.Data;
import java.util.Date;
@Data
public class User {
private Long id; //id
private Integer age; //年龄
private String name;//用户名
private String password;//密码
private String role; //角色
}
HelloController 代码
import com.example.springsecuritydemo.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
public class HelloController {
@RequestMapping("/index")
public String index(ModelMap map) {
map.addAttribute("name","张三");
return "index";
}
@RequestMapping("/test")
public String test(ModelMap map){
User u = new User();
u.setName("张三");
u.setAge(24);
User u1 = new User();
u1.setName("李四");
u1.setAge(35);
User u2 = new User();
u2.setName("nami");
u2.setAge(27);
List userList = new ArrayList<>();
userList.add(u);
userList.add(u1);
userList.add(u2);
map.addAttribute("user",u);
map.addAttribute("userList",userList);
return "test";
}
@PostMapping("/postform")
public String postform(User u){
System.out.println(u.getName());
return "redirect:/index.html";
}
}
resources目录下新建templates目录,templates目录下新建index.html,代码如下
Title
index.html in templates
hello ${name}
templates目录下新建test.html,代码如下
Title
用户姓名:
用户年龄:
用户生日:
用户生日:
用户姓名:
用户年龄:
用户生日:
URL:
多多关照
young
old
| 姓名 | 年龄 | 备注 | 生日 |
|---|---|---|---|
resources下新建static目录,static下新建index.html,内容如下
Title
index.html in static



