spring boot 使用velocity、freeMarker模板创建html页面返回给前端

简单几步,实现在spring boot中使用velocity或freeMarker模板构造页面后返回给前端:


1、引入依赖和创建templates目录:
Velocity: http://blog.csdn.net/clementad/article/details/51819647
FreeMarker: http://blog.csdn.net/clementad/article/details/51942629

2、创建模板文件:

创建两个文件,一个对应于正常的页面,文件名:

Velocity:welcome.vm

FreeMarker:welcome.ftl

<!DOCTYPE html>
<html>
<body>
<h4>亲爱的${toUserName},你好!</h4>

<p style="color:blue;"> ${message}</p>

祝:开心!
</br>
${fromUserName}
</br>
${time}

</body>
</html>

一个对应于错误的页面(ulr输入错误时自动输出这个页面,文件名:error.vm或error.ftl):

<!DOCTYPE html>
<html>
<body>
	<p>有错误: ${status} ${error}</p>
</body>
</html>


3、Controller代码:
package com.xjj.web.controller;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xjj.util.XDateUtils;

@Controller
@RequestMapping("/web")
public class WebController {
	
	@RequestMapping("/hi")
	public String hi(Map<String, Object> model) {
		model.put("time", XDateUtils.nowToString());
		model.put("message", "这是测试的内容。。。");
		model.put("toUserName", "张三");
		model.put("fromUserName", "老许");
		return "welcome"; //自动寻找resources/templates中名字为welcome.vm的文件作为模板,拼装后返回
	}
}

4、测试:
浏览器中输入url:http://localhost:8082/web/hi
结果:

如果输入一个不存在的url,比如http://localhost:8082/web/hello,结果如下:


源代码参考: https://github.com/xujijun/my-spring-boot

附:

velocity官网: http://velocity.apache.org/

velocity语法参考:http://velocity.apache.org/engine/devel/vtl-reference.html

FreeMarker官网:http://freemarker.org/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值