使用Kotlin + Spring Boot 2.1.0 + Thymeleaf + IntelliJ IDEA + Gradle来创建Hello World应用
摘要
使用 IntelliJ IDEA 编写程序,使用 Kotlin + Spring Boot 2.1.0 + Thymeleaf 来显示 Hello World。
环境
- 
- IntelliJ IDEA Community Version 2018.2.5
 
- 
- Kotlin plugin version 1.3.0-release-IJ2018.2-1
 
- 
- Gradle 4.8.1
 
- 
- Spring Boot 2.1.0
 
- Thymeleaf 3.0.11
使用Spring Initializr生成项目的模板。
使用 Spring Initializr 并指定以下内容后,点击「生成项目」。
- 
- Generate a 「Gradle Project」 with 「Kotlin」 and Spring Boot 「2.1.0」
 
- 
- Group: com.example
 
- 
- Artifact: demo
 
- Dependencies: Web, Thymeleaf

可以下载项目的zip文件。
项目文件
解压缩已下载的 zip 文件。
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   ├── kotlin
    │   │   └── com
    │   │       └── example
    │   │           └── demo
    │   │               └── DemoApplication.kt
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── kotlin
            └── com
                └── example
                    └── demo
                        └── DemoApplicationTests.kt
构建文件 build.gradle
由于本次使用了 Kotlin 1.3.0 版本,因此可以将 kotlinVersion = ‘1.3.0’ 修改为 kotlinVersion = ‘1.3.0’,但不必修正。
buildscript {
    ext {
        kotlinVersion = '1.2.70'
        springBootVersion = '2.1.0.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
        classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
    }
}
apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}
repositories {
    mavenCentral()
}
dependencies {
    implementation('org.springframework.boot:spring-boot-starter-thymeleaf')
    implementation('org.springframework.boot:spring-boot-starter-web')
    implementation('com.fasterxml.jackson.module:jackson-module-kotlin')
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    testImplementation('org.springframework.boot:spring-boot-starter-test')
}
应用程序类 DemoApplication.kt。
不做任何特別修改。
package com.example.demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}
在IntelliJ IDEA中创建项目
在IntelliJ IDEA中,使用”Import Project”选项来指定build.gradle文件。

勾选”自动导入”并导入。

执行原型程序
在IntelliJ IDEA的菜单中,选择“视图”→“工具窗口”→“Gradle”,然后打开Gradle窗口。

在Gradle窗口中,选择Tasks → application → bootRun,右键点击并选择运行’demo [bootRun]’。

运行后,Spring Boot 的消息将会在运行窗口中显示如下。
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)
随后会显示类似于“Tomcat已在端口8080(http)上启动,上下文路径为空”和“DemoApplicationKt已启动”的日志。
当访问http://localhost:8080时,将显示以下消息。尽管服务器已启动,但程序内容为空。
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
添加Hello World的代码
添加两个文件 HelloController.kt 和 hello_name.html,实现 Hello World。

添加控制器类(Controller class)
将以下的HelloController类添加到src/main/kotlin/com/example/demo/HelloController.kt中。

package com.example.demo
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
@Controller
class HelloController {
    @RequestMapping(value = ["/hello"], method = [RequestMethod.GET])
    @ResponseBody
    fun hello_world(): String {
        return "hello, world"
    }
    @RequestMapping(value = ["/hello/{name}"], method = [RequestMethod.GET])
    fun hello_name(@PathVariable name: String, model: Model): String {
        model.addAttribute("name", name)
        return "hello_name" // Thymeleaf テンプレートファイル名
    }
}
添加 Thymeleaf 的模板文件
请将以下HTML模板文件添加到src/main/resources/templates/hello_name.html。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Hello, [[${name}]]</title>
</head>
<body>
<p>Hello, [[${name}]]</p>
</body>
</html>
运行Hello World程序
再次执行程序。

访问 http://localhost:8080/hello 会显示”你好,世界”。

当访问 http://localhost:8080/hello/hoge 时,会显示“你好,hoge”。

在网址的“hoge”部分可以指定任意的字符串。

请提供相关信息。
- 
- IntelliJ IDEA: The Java IDE for Professional Developers by JetBrains
 
- Spring Boot
 
    