Freemarker
Springboot中不推荐使用jsp。所以表现层页面可以使用模板引擎实现。Spring Boot支持的模板类型有: velocity、freemarker、Thymeleaf等 其中对velocity的支持以及设置成过期状态,也就意味中springboot已经抛弃的velocity,所以在springboot中如果要编写页面的话应该使用freemarker或者Thymeleaf,本教程中使用freemarker。
freemarker和thymeleaf是模板引擎。在早前我们使用Struts或者SpringMVC等框架的时候,使用的都是jsp,jsp的本质其实就是一个Servlet,其中的数据需要在后端进行渲染,然后再在客户端显示,效率比较低下。而模板引擎恰恰相反,其中的数据渲染是在客户端,效率方面比较理想一点。前后端不分离的话用模板引擎比较好,前后端分离的话其实用处并不大很大。Spring官方比较推荐的是thymeleaf,其文件后缀是html。本篇文章我们主要来看看SpringBoot整合freemarker,SpringBoot整合thymeleaf我们将在后面的文章中讲解。
pom文件引入以下依赖
<!-- 添加freemarker的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
编写freemarker模板
注意:模板必须放到src/main/resources/templates目录下。并且模板扩展名必须为ftl。
<html>
<head>
<title>展示用户列表</title>
</head>
<body>
<table border="1">
<tr>
<th>用户id</th>
<th>用户名</th>
<th>密码</th>
<th>用户姓名</th>
</tr>
<#list userList as user>
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.name}</td>
</tr>
</#list>
</table>
<img src="/img/1.jpg">
</body>
</html>
代码编写
@Controller
public class UserController {
@Autowired
private UserService userService;
// http://localhost:8080//user/list
@RequestMapping("/user/list")
public String showUserList(Model model) {
// 取用户列表
List<User> userList = userService.findUserList();
// 把用户列表传递给视图
model.addAttribute("userList", userList);
// 返回逻辑视图
return "user";
}
}
http://localhost:8080//user/list
访问静态资源
网页中可能会用到,图片、css、js等静态资源。
需要把静态资源放到src/main/resources下的static目录下
访问静态资源