一 Thymeleaf的特点
Thymeleaf是通过特定的语法对html的标记做渲染。
二 编写controller
/**
* Thymeleaf入门案例
*/
@Controller
public class DemoController {
@RequestMapping("/showInfo")
public String showInfo (Model model) {
model.addAttribute("msg", "Thymeleaf第一个案例");
return "index";
}
}
三 创建视图(index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Thymeleaf入门</title>
</head>
<body>
<!-- th:表示Thymeleaf前缀字符,text表示向页面输入内容 -->
<span th:text="Hello"></span>
<hr/>
<span th:text="${msg}"></span>
</body>
</html>
四 编写启动类
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
五 启动项目测试
在浏览器中输入http://localhost:8080/showInfo
六 可能出现的异常及错误解决方案
1 异常
如果导入的jar包是低版本的Thymeleaf时,运行项目,当在浏览器中执行时,后台可能会报如下异常。
org.xml.sax.SAXParseException:元素类型"meta"必须由匹配的结束标记"</meta>"终止
2 解决方案
第一种解决方案
在对应的html文件中添加结束标签,如:<meta charset="UTF-8" />
第二种解决方案
修改Thymeleaf的版本,将Thymeleaf升级到3.0版本及以上即可。具体方法为在pom.xml中的properties标签指定需要的版本就可以,比如:
<properties>
<tymeleaf.version>3.0.2.RELEASE</tymeleaf.version>
</properties>