SpringBoot四:整合Freemarker

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目录下
在这里插入图片描述

访问静态资源

在这里插入图片描述
在这里插入图片描述

代码托管:springboot_freemarker

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值