Spring boot 使用Thymeleaf对web视图进行渲染

1.5.2版本的spring boot对velocity不支持。故使用官推thymeleaf进行视图渲染。

Thymeleaf

Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。也就是说它即可以在在浏览器查看页面的静态效果,也可以在服务器查看带数据的动态页面效果。

基本配置

build.gradle配置

"org.springframework.boot:spring-boot-starter-thymeleaf"

application.properties配置

spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.content-type=text/html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.thymeleaf

cache表示时候使用缓存,一般来说,开发阶段都设置为false,即每次都会重新请求服务器,对页面进行渲染,而不是使用缓存。
prefix表示模版所在位置,spring boot提供的默认静态位置一般在resources下。
suffix表示模版后缀。

两个简单的渲染展示

@Controller
@RequestMapping(value = "/page")
public class PageCtroller {

    static final private List<Customer> customers = Lists.newArrayList(new Customer(1, "siva01", 12), 
            new Customer(2, "siva02", 18), new Customer(3, "siva10", 25));

    @RequestMapping(value = "/index")
    public String getCustomerList(ModelMap map) {
        map.addAttribute("name", "sivannnn");
        return "index";
    }

    @RequestMapping(value = "/customers")
    public String customers(ModelMap map) {
        map.addAttribute("data", customers);
        return "customers";
    }
}

注意一定不要使用@RestController!!

单个字段渲染
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello!, ' + ${name} + '!'" >hello</p>
</body>
</html>
表数据渲染
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <table>
        <caption>客户列表</caption>
            <thead>
                <tr>
                    <th scope="col">ID</th>
                    <th scope="col">姓名</th>
                    <th scope="col">年龄</th>

                </tr>
            </thead>
            <tbody>
                <tr th:each="customers : ${data}">
                    <td th:text="${customers.id}">01</td>
                    <td th:text="${customers.name}">朱遇平</td>
                    <td th:text="${customers.age}">java</td>
                </tr> 
            </tbody>
    </table>
</body>
</html>

访问http://localhost:8080/page/index即可看见渲染效果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值