Spring Boot 与 kotlin 使用Thymeleaf模板引擎渲染web视图

961 阅读5分钟
原文链接: mp.weixin.qq.com

在《使用Spring Boot和Kotlin创建RESTfull API》一文中,我们完成了一个简单的RESTful 服务,体验了Spring Boot 与 kotlin结合的神力,但是往往我们也需要web的支持,那么本篇就在上一个文章的基础上介绍Spring Boot 与 kotlin 使用Thymeleaf模板引擎渲染web视图。

静态资源访问

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源,使用Spring Boot 与 kotlin如何去支持这些静态资源?,很简单。

默认配置

Spring Boot默认提供静态资源目录位置需置于 classpath下,目录名需符合如下规则:

                            
  1. / static

  2. / public

  3. / resources

  4. / META-INF /resources

例如:我们可以在src/main/resources/目录下创建static文件夹,在该位置放置一个图片文件 rubg.jpg。启动程序后,尝试访问http://localhost:8080/ruby.jpg。如能显示图片,配置成功。

渲染Web页面

之前通过 @RestController处理请求,返回的内容为json对象。如果需要渲染  html页面,要如何实现呢?

模板引擎

在 SpringBoot推荐的模板引擎下,我们可以很快的上手开发动态网站。

SpringBoot提供了默认配置的模板引擎主要有以下几种:

                                        
  1. Thymeleaf

  2. FreeMarker

  3. Groovy

  4. Mustache

当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为: src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。

Thymeleaf

Thymeleaf是一个  XML /XHTML /HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。

Thymeleaf提供了一个用于整合  Spring MVC 的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。

示例模板:

  1. <!DOCTYPE html>

  2. <html xmlns:th="http://www.w3.org/1999/xhtml">

  3. <head lang="en">

  4.    <meta charset="UTF-8" />

  5.    <title>quanke.name</title>

  6. </head>

  7. <body>

  8. <h1 th:text="${host}">Hello World</h1>

  9. </body>

  10. </html>

可以看到Thymeleaf主要以属性的方式加入到html标签中,浏览器在解析html时,当检查到没有的属性时候会忽略,所以Thymeleaf的模板可以通过浏览器直接打开展现,这样非常有利于前后端的分离。

在Spring Boot中使用Thymeleaf,只需要引入下面依赖,并在默认的模板路径 src/main/resources/templates下编写模板文件即可完成。

                                                    
  1. compile "org.springframework.boot:spring-boot-starter-thymeleaf:$spring_boot_version"

完整的 build.gradle

                                                        
  1. group 'name.quanke.kotlin'

  2. version '1.0-SNAPSHOT'

  3. buildscript {

  4.    ext .kotlin_version = '1.2.10'

  5.    ext .spring_boot_version = '1.5.4.RELEASE'

  6.    repositories {

  7.        mavenCentral ()

  8.     }

  9.    dependencies {

  10.        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

  11.        classpath ("org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version" )

  12. //        Kotlin整合SpringBoot的默认无参构造函数,默认把所有的类设置open类插件

  13.        classpath ("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version" )

  14.        classpath ("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" )

  15.     }

  16. }

  17. apply plugin : 'kotlin'

  18. apply plugin : "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin

  19. apply plugin : 'org.springframework.boot'

  20. jar {

  21.    baseName = 'chapter11-5-1-service'

  22.    version = '0.1.0'

  23. }

  24. repositories {

  25.    mavenCentral ()

  26. }

  27. dependencies {

  28.    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"

  29.    compile "org.springframework.boot:spring-boot-starter-web:$spring_boot_version"

  30.    compile "org.springframework.boot:spring-boot-starter-thymeleaf:$spring_boot_version"

  31. //    compile "com.fasterxml.jackson.module:jackson-module-kotlin:$kotlin_version"

  32.    testCompile "org.springframework.boot:spring-boot-starter-test:$spring_boot_version"

  33.    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"

  34. }

  35. compileKotlin {

  36.    kotlinOptions .jvmTarget = "1.8"

  37. }

  38. compileTestKotlin {

  39.    kotlinOptions .jvmTarget = "1.8"

  40. }

举个例子:通过Thymeleaf渲染一个页面。

  1. import org.springframework.stereotype.Controller

  2. import org.springframework.ui.ModelMap

  3. import org.springframework.web.bind.annotation.RequestMapping

  4. /**

  5. * Created by http://quanke.name on 2018/1/10.

  6. */

  7. @Controller

  8. class HelloController {

  9.    @RequestMapping("/")

  10.    fun index(map: ModelMap): String {

  11. //        / 加入一个属性,用来在模板中读取

  12.        map.addAttribute("host", "http://quanke.name")

  13.        // return模板文件的名称,对应src/main/resources/templates/index.html

  14.        return "index"

  15.    }

  16. }

默认在 src/main/resources/templates目录下增加  index .html文件

                                                            
  1. <!DOCTYPE html>

  2. <html xmlns:th="http://www.w3.org/1999/xhtml" >

  3. <head lang="en" >

  4.     <meta charset= "UTF-8" />

  5.     <title>quanke.name </title>

  6. </head>

  7. <body>

  8. <h1 th:text="${host}" >Hello World </h1>

  9. </body>

  10. </html>

增加使用 kotlin语言实现的  Spring Boot启动方法:

                                                                
  1. import org.springframework.boot .SpringApplication

  2. import org.springframework.boot .autoconfigure .SpringBootApplication

  3. /**

  4. * Created by http://quanke.name on 2018/1/9.

  5. */

  6. @SpringBootApplication

  7. class Application

  8. fun main (args : Array< String>) {

  9.     SpringApplication. run( Application:: class. java, * args)

  10. }

如上页面,直接打开html页面展现Hello World,但是启动程序后,访问http://localhost:8080/,则是展示Controller中host的值:http://quanke.name,做到了不破坏HTML自身内容的数据逻辑分离。

更多 Thymeleaf的页面语法,还请访问Thymeleaf的官方文档查询使用。

Thymeleaf的默认参数配置

如有需要修改默认配置的时候,只需复制下面要修改的属性到 application.yml中,并修改成需要的值,如修改模板文件的扩展名,修改默认的模板路径等。

                                                                        
  1. # Enable template caching.

  2. spring .thymeleaf .cache =true

  3. # Check that the templates location exists.

  4. spring .thymeleaf .check -template -location =true

  5. # Content-Type value.

  6. spring .thymeleaf .content -type =text /html

  7. # Enable MVC Thymeleaf view resolution.

  8. spring .thymeleaf .enabled =true

  9. # Template encoding.

  10. spring .thymeleaf .encoding =UTF -8

  11. # Comma-separated list of view names that should be excluded from resolution.

  12. spring .thymeleaf .excluded -view -names =

  13. # Template mode to be applied to templates. See also StandardTemplateModeHandlers.

  14. spring .thymeleaf .mode =HTML5

  15. # Prefix that gets prepended to view names when building a URL.

  16. spring .thymeleaf .prefix =classpath :/templates/

  17. # Suffix that gets appended to view names when building a URL.

  18. # spring.thymeleaf.suffix=.html  

  19. # spring.thymeleaf.template-resolver-order=

  20. # Order of the template resolver in the chain.

  21. # spring.thymeleaf.view-names=

  22. # Comma-separated list of view names that can be resolved.

测试环境或者开发环境避免出现不可预期问题一般设置: spring.thymeleaf.cache=true

支持JSP的配置

Spring Boot并不建议使用,如果需要,参考此工程:JSP支持

总的来说 Kotlin 对于  Spring Boot 的支持非常好,只需要把Java语言的  Spring Boot使用,翻译成  kotlin就可以。


相关阅读:

我的第一个Kotlin应用

使用Spring Boot和Kotlin创建RESTfull API


全科龙婷▼升职加薪