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

时间:2017/8/17 15:21:00来源:互联网 作者:flyso 点击: 2385 次

Thymeleaf

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

基本配置

build.gradle配置

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

application.properties配置

spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.content-type=text/html
spring.thymeleaf.encoding=UTF-8spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.thymeleaf
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

注意一定不要使用@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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

表数据渲染

<!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>


Copyright © 2005 - 2016 flyso.cn. 飞搜 版权所有 鄂ICP备11002783号-3