Spring Boot 使用 Thymeleaf模板

Spring Boot 使用 Thymeleaf模板

Thymeleaf

Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。

  • 首先在pom.xml文件中增加对Thymeleaf的依赖
<!-- 增加Thymeleaf的模板使用 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 增加application.yml配置
spring:
  thymeleaf:
    # Enable template caching.
    cache: true
    # Check that the templates location exists.
    check-template-location: true
    # Content-Type value.
    content-type: text/html
    # Enable MVC Thymeleaf view resolution.
    enabled: true
    # Template encoding.
    encoding: UTF-8
    # Comma-separated list of view names that should be excluded from resolution.
    #excluded-view-names:
    # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
    mode: HTML5
    # Prefix that gets prepended to view names when building a URL.
    prefix: classpath:/templates/thymeleaf/
    # Suffix that gets appended to view names when building a URL.
    suffix: .html
    # Order of the template resolver in the chain.
    #template-resolver-order:
    # Comma-separated list of view names that can be resolved.
    #view-names:

配置prefix时一定要注意 classpath:/templates/thymeleaf/ 最后的这个/一定要加, 否则解析的时候会模板不存在,解析不了的情况
Thymeleaf error

  • 编写Controller.java文件
package com.imooc.controller;

import com.imooc.properties.GirlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 因为使用了Thymeleaf模板,所以不能使用RestController
 * Created by ZhouBJ on 2017/9/29.
 */
@Controller
public class HelloController {

    /**
     * 使用Thymeleaf模板
     * @param modelMap
     * @return
     */
    @RequestMapping(value="/hello/index", method = RequestMethod.GET)
    public String helloIndex( ModelMap modelMap){
        // 加入一个属性,用来在模板中读取 - 此处的值将会覆盖模板页面本身已经存在的值
        modelMap.addAttribute( "title", "标题-测试页面" );
        modelMap.addAttribute( "host", "demo.baomidou.com:8080" );
        // return模板文件的名称,对应src/main/resources/templates/index.html
        return "index";
    }
}
  • 修改index.html
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
  <meta charset="UTF-8" />
  <title th:text="${title}">Hello,测试页</title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

效果展示:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值