閱讀898 返回首頁    go 技術社區[雲棲]


《精通Spring MVC 4》——2.4 使用Thymeleaf

本節書摘來自異步社區《精通Spring MVC 4》一書中的第2章,第2.4節,作者:【美】Geoffroy Warin著,更多章節內容可以訪問雲棲社區“異步社區”公眾號查看

2.4 使用Thymeleaf

Thymeleaf是一個模板引擎,在Spring社區中,它備受關注。

它的成功在很大程度上要歸因於對用戶友好的語法(它幾乎就是HTML)以及擴展的便利性。

如表2-1所示,現在有各種可用的擴展,並且能夠與Spring Boot進行集成。

screenshot

閑言少敘,現在我們將spring-boot-starter-thymeleaf依賴添加進來,這樣就能啟動Thymeleaf模板引擎了:

buildscript {
    ext {
        springBootVersion = '1.2.5.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
        classpath("io.spring.gradle:dependency-management-
plugin:0.5.1.RELEASE")
    }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'io.spring.dependency-management'

jar {
    baseName = 'masterSpringMvc'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
    testCompile 'org.springframework.boot:spring-boot-starter-test'
}

eclipse {
    classpath {
         containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
         containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.
eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

第一個頁麵
現在,我們將第一個頁麵添加到應用之中,我們將其放到src/main/resources/templates中,並將其命名為resultPage.html:

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8"/>
    <title>Hello thymeleaf</title>
</head>
<body>
    <span th:text="|Hello thymeleaf|">Hello html</span>
</body>
</html>

我們首先能夠看到Thymeleaf與HTML結合得非常好,它的語法看上去也非常自然。

th:text的值放在兩個豎線中間,這意味著文本中所有的值都會連接在一起。

看上去,這可能有點怪異,但實際上,我們很少在頁麵中進行硬編碼,因此,Thymeleaf在這裏采用了具有一定傾向性的設計。

對於Web設計人員來說,Thymeleaf有一項很大的優勢,那就是在服務器沒有運行的時候,模板中所有的動態內容都可以采用一個默認值。資源URL可以采用相對的路徑來指定,每個標簽都可以包含占位符。在前麵的樣例裏麵,如果是在應用的上下文中,那麼文本“Hello html”將不會顯示,但是如果直接在Web瀏覽器中打開這個文件的話,那麼它就會顯示了。

為了加快開發速度,在application.properties文件中添加該屬性:

spring.thymeleaf.cache=false
這將會禁止啟用視圖緩存,每次訪問的時候都會重新加載模板。

當然,在部署到生產環境時,該項配置需要禁用。在第8章時,我們會再進行設置。

screenshot

如果禁用了緩存,在修改視圖之後,隻需在Eclipse中進行保存或者在IntelliJ中使用Build > Make Project操作就可以刷新視圖。
最後,需要修改HelloController類,它必須要導航至我們新建的視圖,而不是展現簡單的文本。為了完成該功能,需要移除@ResponseBody注解。這樣做完之後,如果再次返回字符串的話,就會告訴Spring MVC要將這個字符串映射為視圖名,而不是在響應中直接展現特定的模型。

我們的控製器將會變為如下所示:

@Controller
public class HelloController {

    @RequestMapping("/")
    public String hello() {
        return "resultPage";
    }
}

在本例中,控製器會將用戶轉移到名為resultPage的視圖中,ViewResolver接口會將這個名字與我們的視圖進行關聯。

再次啟動應用並轉至https://localhost:8080。

你將會看到如圖2-2所示的頁麵。

screenshot

圖2-2

最後更新:2017-05-27 15:31:30

  上一篇:go  《精通Spring MVC 4》——2.5 Spring MVC架構
  下一篇:go  《精通Spring MVC 4》——2.3 Spring MVC 1-0-1