spring整合视图
1.Thymeleaf
1.导入依赖
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.通过application.properties配置Thymeleaf
#设置缓存是否开启开发的时候可以false默认true
spring.thymeleaf.cache=false
#检查模板是否存在
spring.thymeleaf.check-template=true
#查看模板位置
spring.thymeleaf.check-template-location=true
#设置模板编码
spring.thymeleaf.encoding=UTF-8
#设置模板位置
spring.thymeleaf.prefix=classpath:/templates/
#设置Content-type
spring.thymeleaf.servlet.content-type=text/html
#指定后缀
spring.thymeleaf.suffix=.html
3.创建实体类(Book类)
public class Book {
private Integer bid;
private String bname;
private String author;
private Double price;
}
4.创建控制器BookController方法返回类型是ModeAndView类型
@Controller
public class BookController {
@RequestMapping("/books")
public ModelAndView books(){
//模型和视图
ModelAndView mav = new ModelAndView();
//打桩数据
Book book1 = new Book(1,"九阴真经","周芷若",88.8D);
Book book2 = new Book(2,"九阳神功","火工头陀",98.8D);
Book book3 = new Book(3,"降龙十八掌","乔峰",188.8D);
//创建集合
List<Book> list =new ArrayList<>();
//将数据存到集合
list.add(book1);
list.add(book2);
list.add(book3);
//将数据放入模型和视图
mav.addObject("books",list);//页面上遍历用的名字
//设置视图
mav.setViewName("books");//展示页面的名字
return mav;
}
}
5.前端页面
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" th:width="600px">
<tr>
<td>编号</td>
<td>书名</td>
<td>作者</td>
<td>价格</td>
</tr>
<tr th:each="book:${books}">
<td th:text="${book.bid}"></td>
<td th:text="${book.bname}"></td>
<td th:text="${book.author}"></td>
<td th:text="${book.price}"></td>
</tr>
</table>
</body>
</html>
2.FreeMarker
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.通过application.properties配置freemarker
#设置httpServletRequest 是否检查Controller中的Model
spring.freemarker.allow-request-override=false
#设置httpSession 是否去检查Controller中的model同名项
spring.freemarker.allow-session-override=false
#是否开启缓存
spring.freemarker.cache=false
#文件编码
spring.freemarker.charset=UTF-8
#检查模板位置
spring.freemarker.check-template-location=true
#设置Content-type的值
spring.freemarker.content-type=text/html
#是否经httpsetvletResuest中的值加入model
spring.freemarker.expose-request-attributes=false
#是否将httpSession中的值加入model中
spring.freemarker.expose-session-attributes=false
#模板文件位置
spring.freemarker.template-loader-path=classpath:/templates/
#设置文件后缀
spring.freemarker.suffix=.ftl
3.创建实体类(Book)
//与上边一样
4.创建控制类
//与上边一样
5.前端页面(注意语法)(文件后缀为ftl)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1" width="600px">
<tr>
<td>编号</td>
<td>书名</td>
<td>作者</td>
<td>价格</td>
</tr>
<#if books ?? &&(books?size>0)>
<#list books as book>
<tr >
<td >${book.bid}</td>
<td >${book.bname}</td>
<td >${book.author}</td>
<td >${book.price}</td>
</tr>
</#list>
</#if>
</table>
</body>
</html>