Spring Boot集成Thymeleaf的方法
一、Java模板引擎
模板引擎(這里特指用于Web開發(fā)的模板引擎)是為了使用戶界面與業(yè)務數(shù)據(jù)(內(nèi)容)分離而產(chǎn)生的,它可以生成特定格式的文檔,用于網(wǎng)站的模板引擎就會生成一個標準的HTML文檔。
在java中,主要的模板引擎有JSP、Thymeleaf、FreeMarker、Velocity等。
雖然隨著前后端分離的崛起和流行,模板引擎已遭受到冷落,但不少舊項目依然使用java的模板引擎渲染界面,而偶爾自己寫一些練手項目,使用模板引擎也比起前后端分離要來的快速。
本系列會分別講解SpringBoot怎么集成JSP、Thymeleaf和FreeMarker,至于Velocity,高版本的SpringBoot已經(jīng)不支持Velocity了,這里也就不進行講解了。
而這一篇,主要講解Spring Boot如何集成Thymeleaf。
二、Spring Boot集成Thymeleaf
首先我們要引入依賴,除了核心的web依賴外,只需引入thymeleaf的statrer即可。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- thymeleaf模板 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
然后就是配置文件了。spring.thymeleaf下配置視圖文件目錄prefix以及文件后綴suffix,如果是本地開發(fā),cache可以設置為false關(guān)閉緩存,避免修改文件后需要重新啟動服務。
server: port: 10900 spring: profiles: active: dev thymeleaf: prefix: classpath:/templates/ check-template-location: true #是否檢查模板位置是否存在 suffix: .html encoding: utf-8 #模板編碼 servlet: content-type: text/html mode: HTML5 cache: false #禁用緩存,本地開發(fā)設置為false,避免修改后重啟服務器
然后resoucres目錄下新建templates目錄,分別新建了hello.html和mv.html文件。
<h3>hello thymeleaf</h3>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<h3>mv thymeleaf</h3>
<span>I'm <span th:text="${name}"></span> from mv method</span>
</html>
這里主要講解如何集成Thymeleaf,不對Thymeleaf語法做過多的講解,所以僅僅提供了兩個簡單的html文件作為演示。
接著再創(chuàng)建Controller類路由頁面,該類十分簡單,跳轉(zhuǎn)hello頁面,以及攜帶name=imyang跳轉(zhuǎn)mv頁面。
@Controller
@RequestMapping("index")
public class IndexApi {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
@RequestMapping("/mv")
public ModelAndView mv(){
ModelAndView mv = new ModelAndView("mv");
mv.addObject("name","yanger");
return mv;
}
}
啟動項目,分別訪問http://localhost:10900/index/hello和http://localhost:10900/index/mv,可以看到已經(jīng)可以展示頁面信息了。

源碼地址:https://github.com/imyanger/springboot-project/tree/master/p18-springboot-thymeleaf
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java使用Process調(diào)用exe程序及Process.waitFor()死鎖問題解決
在編寫Java程序時,有時候我們需要調(diào)用其他的諸如exe,shell這樣的程序或腳本,下面這篇文章主要給大家介紹了關(guān)于java使用Process調(diào)用exe程序及Process.waitFor()死鎖問題解決的相關(guān)資料,需要的朋友可以參考下2022-12-12
MyBatis關(guān)聯(lián)查詢的實現(xiàn)
MyBatis可以通過定義多個表的關(guān)聯(lián)關(guān)系,實現(xiàn)多表查詢,本文主要介紹了MyBatis關(guān)聯(lián)查詢的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-11-11

