Springboot整合thymeleaf模板
Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用。
Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。Thymeleaf的可扩展性也非常棒。你可以使用它定义自己的模板属性集合,这样就可以计算自定义表达式并使用自定义逻辑。这意味着Thymeleaf还可以作为模板引擎框架。
Thymeleaf的模板还可以用作工作原型,Thymeleaf会在运行期替换掉静态值。例如下面的html文件,当作为静态文件时,product name显示为Red Chair,当运行在容器中并提供product这个对象时,product name的值会自动替换为product.description对应的值。下面就简单的讲一讲springboot整合thymeleaf模板。
1.引入依赖
在maven(pom.xml)中直接引入:
1
2 org.springframework.boot
3 spring-boot-starter-thymeleaf
4
也可以在创建项目时候勾选thymeleaf模板,这样会自动生成。
2.配置视图解析器
(1)默认
spring-boot很多配置都有默认配置,比如默认页面映射路径为
classpath:/templates/*.html
同样静态文件路径为
classpath:/static/
(2)自定义
在application.properties(或者application.yml)中可以配置thymeleaf模板解析器属性.就像使用springMVC的JSP解析器配置一样
1 #thymeleaf start
2 spring.thymeleaf.mode=HTML5
3 spring.thymeleaf.encoding=UTF-8
4 spring.thymeleaf.content-type=text/html
5 #开发时关闭缓存,不然没法看到实时页面
6 spring.thymeleaf.cache=false
7 #thymeleaf end
具体可以配置的参数可以查看 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 这个类,上面的配置实际上就是注入到该类中的属性值.
3.编写demo来说明使用方法
测试
访问 localhost:8080/ 这个地址,会直接跳转到 index.html 页面,并显示如下
其实不要使用spring boot的@RestController注解,直接使用spring原来的注解@Controller就可以了。示例如下:
@Controller
public class ActionController {
@RequestMapping(value = “/action”,method = RequestMethod.GET)
public String index(){
return "login";
}
}
如果你的项目如什么都没有配,那么你想跳到login.html时,语句必须是 return “login.html” ,否则它会报错 。因为找不到login文件。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"