Thymeleaf Java is a template engine that can handle HTML, XML, JavaScript, CSS and other text code, the front and rear end to realize the function of data communication.
1. Add dependence:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. Thymeleaf be xml configuration parameters:
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
3. Create the solid model and configuration of the controller class
Create a class named Book of:
public class Book {
private int id;
private String name;
private String author;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
Then create Controller class, it will return a view object model, which instance of the Book class can add
import com.example.demo.bean.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
@Controller
public class BookController {
@GetMapping("/books") //程序请求入口
public ModelAndView books(){
List<Book> books = new ArrayList<>();
Book b1 = new Book();
b1.setId(250);
b1.setName("Java从入门到放弃");
b1.setAuthor("詹姆斯·高斯林");
Book b2 = new Book();
b2.setId(251);
b2.setName("Spring boot 开发实战");
b2.setAuthor("高级程序员");
books.add(b1);
books.add(b2);
ModelAndView mv = new ModelAndView();
mv.addObject("books",books); //添加名为books的对象
mv.setViewName("books"); //设置视图名称为books
return mv;
}
}
4. Create named books in the templates directory html file (the file name as the name of the view must be set above):
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1px">
<tr>
<td>图书编号</td>
<td>书籍名称</td>
<td>作者</td>
</tr>
<!--thymeleaf语法如下-->
<tr th:each="book:${books}">
<td th:text="${book.id}"></td>
<td th:text="${book.name}"></td>
<td th:text="${book.author}"></td>
</tr>
</table>
</body>
</html>
5. Finally start the program, open the browser / books directory, you can visit our page thymeleaf