Spring Boot 使用 Thymeleaf模板

来源:互联网 发布:sql存储过程详细教学 编辑:程序博客网 时间:2024/06/01 10:23

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. */@Controllerpublic 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>

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

原创粉丝点击