Thymeleaf的使用
一、Thymeleaf是什么
Thymeleaf是一个模板引擎。这个模板引擎就跟 jsp几乎一模一样 。
无论是jsp还是模板引擎,他们适用的场景都是页面和后台代码在一个服务器上的这种模式 同步模式。这种开发并不适合于异步模式(这种模式和前后分离有很大的区别)。
二、Thymeleaf作用
前端页面的展示。
注意:Springboot对jsp的支持不是很好 ,里面推荐使用的是模板引擎。
Thymeleaf这个是不能直接访问的,需要通过控制器转发进行访问。
三、Thymeleaf在Springboot下的使用
1、新建子工程(之前已经说了,这里只是方便演示,可以单独去建一个项目)
2、导包
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- 这个是方便类的创建,不用的话就自己写getset以及其他的方法 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>
3、编写启动类Application
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
4、编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
}
5、编写测试类
1.简单的前端接受
1.1、测试类
@Controller
public class UserController {
@RequestMapping("/toTest1")
public String toDemo1(Model model){
model.addAttribute("username","西沟");
return "/test1.html";
}
}
1.2、html页面
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <!--简