SpringBoot入门之Thymeleaf的使用

在.net的MVC3 或更高版本等支持 Razor 的框架里使用cshtml,Razor是一种简单的编程语法,用于在网页中嵌入服务器端代码.在使用springboot开发mvc时也有与.net类似的视图引擎.
Spring Boot提供了大量的模板引擎,包含了FreeMarker,Groovy,Thymeleaf,Velocity和Mustache,Spring Boot中推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的Spring MVC的支持。Thymeleaf是一个java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的View层。Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代JSP。
一、Thymeleaf配置
Thymeleaf有哪些属性可以配置呢,我们可以在org.springframework.boot.autoconfigure.thymeleaf下的ThymeleafProperties.class找到属性,springboot约定大于配置,所以在ThymeleafProperties.class中也都有默认值,如果我们想改变默认值可以在application.properties设置。这里用的都是它的默认值。默认路径在templates下,文件是html文件。

 

二、项目引入Thymeleaf

这里还是在上一springboot博客的例子基础上进行修改,这里需要在pom.xml引入Thymeleaf,这里要注意一下,由于用的是spring5,如果引入的Thymeleaf版本不正确就可能会报错,而且不同的spring引入Thymeleaf的artifactId也不一样。

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.9.RELEASE</version>
        </dependency>

同时如果在html页面使用还需要在html增加一行

<html xmlns:th="http://www.thymeleaf.org">

三、测试

这里创建了一个Controller和一个html.Thymeleaf的属性都是用的默认的属性值,如果需要改变可以在resources/application.properties下更改,前缀名是spring.thymeleaf。

package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


//@RestController
@Controller
public class HelloController {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(Model model) {
        model.addAttribute("name", "Cuiyw");
        return "hello";
    }
}
<!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} + '!'" ></p>
</body>
</html>

posted @ 2018-07-01 00:09  社会主义接班人  阅读(7515)  评论(0编辑  收藏  举报