1、配置文件设置
pom文件中加入
<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>
application.properties中加入
spring.thymeleaf.cache=true
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.suffix=.html
配置Thymeleaf
ThymeleafProperties类中放入:
package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING= StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX="classpath:/templates/";
public static final String DEFAULT_SUFFIX=".html";
}
实体类和控制器
package com.example.demo;
public class Books {
private Integer id;
private String name;
private String author;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
@Override
public String toString(){
return "Books[id="+id+",name="+name+",author="+author+"]";
}
}
package com.example.demo;
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<Books> books=new ArrayList<>();
Books b1=new Books();
b1.setId(1);
b1.setName("三国演义");
b1.setAuthor("罗贯中");
Books b2=new Books();
b2.setId(2);
b2.setName("红楼梦");
b2.setAuthor("曹雪芹");
books.add(b1);
books.add(b2);
ModelAndView mv= new ModelAndView();
mv.addObject("books",books);
mv.setViewName("books");
return mv;
}
}
视图层
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>图书列表</title>
</head>
<body>
<table border="1">
<tr>
<td>编号</td>
<td>书名</td>
<td>作者</td>
</tr>
<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>
以上程序做完,在浏览器中输入 http://localhost:8080/books
会得到以下效果