在.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>

最新文章

  1. 【转】将Oracle数据库设置为归档模式
  2. 黄聪:解决Web部署 svg/woff/woff2字体 404错误
  3. requirejs、backbone.js配置
  4. ThreadLocal的基本原理与实现
  5. 关于js一般对象与标配对象
  6. iOS 犄角旮旯的知识
  7. NSString常用方法
  8. Java分页类 Page
  9. HDU_2046——骨牌铺放问题,递推
  10. timeout connect 10000 # default 10 second time out if a backend is not found
  11. 我为什么要创建帮创业者找合伙人的缘创派(ycpai.com)?
  12. PRML 第二章mindmap
  13. git使用教程及github远程仓库管理
  14. 函数响应式编程及ReactiveObjC学习笔记 (四)
  15. [C#] LINQ之GroupBy
  16. 【XSY2745】装饰地板 状压DP 特征多项式
  17. python 的基础 学习 第三
  18. Android学习:ActionBar活动条
  19. grpc-golang实现账号and密码认证
  20. Oracle SQL之 序列使用限制

热门文章

  1. Chapter3_操作符_其他操作符
  2. .NET Core 中使用GB2312编码报错的问题
  3. ABP框架系列之二十一:(Domain-Services-领域服务)
  4. c语言模拟c++的继承和多态
  5. VP-UML系统建模工具研究
  6. array_flip()函数
  7. Javascript高级编程学习笔记(7)—— 函数
  8. vue-cli脚手架项目按需引入elementUI
  9. /etc/sysconfig/iptables 默认配置详解
  10. python中使用queue实现约瑟夫环(约瑟夫问题)求解