标题spring boot 分层开发web应用程序——视图技术thymeleaf
1.引入依赖
pom.xml下添加:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.创建一个User类
public class User {
private String username;
private int age;
private int id;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
3.创建一个Controller类
import com.springproject.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("User")
public class applicationcontroll {
@RequestMapping("detail")
public ModelAndView userdetail1() {
//创建一个modelview对象
ModelAndView mv = new ModelAndView();
//创建一个User类对象,给参数赋值
User user = new User();
user.setUsername("张三");
user.setAge(30);
user.setId(0001);
//设置视图名称
mv.setViewName("UserDe");
//addObjec(String attributeName,Object attributeValue)
//参数一是对象名称,参数二是值的类型
mv.addObject("user", User);
return mv;
}
}
4.xxxx.HTML配置
注:这里有三种用法
<!DOCTYPE html>
<html lang="en"xmlns:th="www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>标准变量表达式:${}(推荐)</h1>//<h1></h1>标题
用户编号:<span th:text="${user.id}"></span><br>
用户姓名:<span th:text="${user.username}"></span><br>
用户年龄:<span th:text="${user.age}"></span><br>
<h1>标准变量表达式:*{}(不推荐)</h1>
<div th:object="${UserDe}">/*UserDe指的是你创建的视图名称和这里设置视图名称
mv.setViewName("UserDe");匹配*/
用户编号:<span th:text="*{id}"></span><br>//使用“*”可以不在前面加对象名
用户姓名:<span th:text="*{username}"></span><br>
用户年龄:<span th:text="*{age}"></span><br>
</div>>
<h1>标准标量表达式:*{}和标准变量表达式:${}(推荐)和用(不推荐)</h1>
用户编号:<span th:text="${id}"></span><br>
用户姓名:<span th:text="${username}"></span><br>
用户年龄:<span th:text="${age}"></span><br>
</body>
</html>
5.项目结构