《Springboot极简教程》使用Spring Boot, JPA, Mysql, ThymeLeaf,gradle, Kotlin快速构建一个CRUD Web App

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 使用Spring Boot, JPA, Mysql, ThymeLeaf,gradle, Kotlin快速构建一个CRUD Web AppThymeleaf is a modern server-side Java template engine for both web and standalone environments.

使用Spring Boot, JPA, Mysql, ThymeLeaf,gradle, Kotlin快速构建一个CRUD Web App

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.

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

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

Thymeleaf官方文档:
http://www.thymeleaf.org/documentation.html

示例模板:

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</td>
      <th th:text="#{msgs.headers.price}">Price</td>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod : ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price,1,2)}">0.99</td>
    </tr>
  </tbody>
</table>

让我们开始吧!

Step1. html页面加入头文件 相应的schema

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

Step2.主页面模板


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<th:block th:include="common/header :: head"></th:block>

<body>
<th:block th:include="common/header :: header"></th:block>

<div th:if="${not #lists.isEmpty(customers)}">
    <h2>Customer List</h2>
    <table id="customersTable" class="table table-striped">
        <thead>
        <tr>
            <th>Id</th>
            <th>FirstName</th>
            <th>LastName</th>
            <th>Created Time</th>
        </tr>
        </thead>

        <tbody>
        <tr th:each="customer : ${customers}">
            <td th:text="${customer.id}"><a href="/product/${product.id}">Id</a></td>
            <td th:text="${customer.firstName}">FirstName</td>
            <td th:text="${customer.lastName}">LastName</td>
            <td th:text="${customer.gmtCreated}">gmtCreated</td>
            <!--<td><a th:href="${ '/product/' + product.id}">View</a></td>-->
            <!--<td><a th:href="${'/product/edit/' + product.id}">Edit</a></td>-->
        </tr>
        </tbody>

    </table>

</div>

<th:block th:include="common/footer :: footer"></th:block>

</body>
</html>


Step3.include common模板说明

common/header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en" th:fragment="head">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.4/css/bootstrap.min.css"
          th:href="@{/webjars/bootstrap/3.3.4/css/bootstrap.min.css}"
          rel="stylesheet" media="screen"/>


    <link href="../../static/css/jquery.dataTables.min.css"
          th:href="@{css/jquery.dataTables.min.css}" rel="stylesheet" media="screen"/>

    <link href="../../static/css/mini_springboot.css"
          th:href="@{css/mini_springboot.css}" rel="stylesheet" media="screen"/>

    <title>Mini SpringBoot Tutorial</title>
</head>

<body>

<div th:fragment="header">
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#" th:href="@{/}">Home</a>
                <ul class="nav navbar-nav">
                    <li><a href="#" th:href="@{/customers.do}">Customers</a></li>
                    <li><a href="#" th:href="@{/customer/new}">Create Customer</a></li>
                </ul>

            </div>
        </div>
    </nav>

    <div class="jumbotron">
        <div class="row text-center">
            <div class="">
                <h1 class="center">Springboot极简教程</h1>
                <h2>Mini SpringBoot Tutorial</h2>
                <h3>Spring Boot Kotlin Thymeleaf Web App</h3>
            </div>
        </div>
        <div class="row text-center">
            <iframe class="iframe" src="https://jason-chen-2017.github.io/Jason-Chen-2017/"></iframe>

            <!--![](../../static/images/home.png)-->
        </div>
    </div>

</div>

</body>
</html>

common/footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>


<div th:fragment="footer">

    <div class="footer">Springboot极简教程, Jason Chen, 2017</div>


    <script src="http://cdn.jsdelivr.net/webjars/jquery/2.1.4/jquery.min.js"
            th:src="@{/webjars/jquery/2.1.4/jquery.min.js}"></script>


    <script src="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.4/js/bootstrap.min.js"
            th:src="@{/webjars/bootstrap/3.3.4/js/bootstrap.min.js}"></script>

    <script src="../../static/js/jquery.dataTables.min.js"
            th:src="@{js/jquery.dataTables.min.js}"></script>

    <script src="../../static/js/mini_springboot.js" th:src="@{js/mini_springboot.js}"></script>

</div>


</body>
</html>

重点看一下thymeleaf的语法设计风格。

写一个th:fragment="{id}"

<div th:fragment="footer">

    。。。

</div>

可以直接在其他页面 th:include

<th:block th:include="common/footer :: footer"></th:block>

<h5>Step4. 配置build.gradle,添加spring-boot-starter-thymeleaf

Spring Boot默认就是使用thymeleaf模板引擎的,所以只需要在build.gradle(pom.xml)加入依赖即可。

version = "0.0.1-SNAPSHOT"

buildscript {

    ext {
        springBootVersion = "1.5.2.RELEASE"
        kotlinVersion = "1.1.0"
    }

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion")
        classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlinVersion")
        classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
    }
}

apply {
    plugin("kotlin")
    plugin("kotlin-spring")
    plugin("kotlin-jpa")
    plugin("org.springframework.boot")
    plugin 'java'
    plugin 'eclipse'
    plugin 'idea'
//    plugin: 'spring-boot'
}

repositories {
    mavenCentral()
}

jar {
    baseName = 'mini_springboot'
    version = '0.0.1'
}


sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
//    compile("com.h2database:h2")
    compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
    compile("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
    compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.8.4")
    testCompile("org.springframework.boot:spring-boot-starter-test")

    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }
    compile("org.springframework.boot:spring-boot-starter-jetty")
    compile("org.springframework.boot:spring-boot-starter-actuator")
    compile('mysql:mysql-connector-java:5.1.13')

    testCompile("junit:junit")

//thymeleaf
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
//WebJars
    compile("org.webjars:bootstrap:3.3.4")
    compile("org.webjars:jquery:2.1.4")
    // https://mvnrepository.com/artifact/org.webjars/datatables
    compile group: 'org.webjars', name: 'datatables', version: '1.10.13'

}


Step5. 新建标准springboot resources目录

Springboot web app有很多约定,根据这些约定,可以省去一大批繁冗的配置。请看标准的工程目录结构

.
├── META-INF
│   └── MANIFEST.MF
├── README.md
├── README_.md
├── build
│   └── kotlin-build
│       └── caches
│           └── version.txt
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── run.bat
├── run.sh
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   ├── kotlin
    │   │   └── jason
    │   │       └── chen
    │   │           └── mini_springboot
    │   │               ├── console
    │   │               │   └── HelloWorld.kt
    │   │               └── restful
    │   │                   ├── Application.kt
    │   │                   ├── biz
    │   │                   │   └── CustomerService.kt
    │   │                   ├── controller
    │   │                   │   └── CustomerController.kt
    │   │                   ├── entity
    │   │                   │   └── Customer.kt
    │   │                   └── utils
    │   │                       └── DateUtils.kt
    │   └── resources
    │       ├── application.properties
    │       ├── application.yml
    │       ├── static
    │       │   ├── css
    │       │   │   ├── jquery.dataTables.min.css
    │       │   │   └── mini_springboot.css
    │       │   ├── images
    │       │   │   ├── home.png
    │       │   │   ├── sort_asc.png
    │       │   │   ├── sort_both.png
    │       │   │   └── sort_desc.png
    │       │   └── js
    │       │       ├── jquery.dataTables.min.js
    │       │       └── mini_springboot.js
    │       └── templates
    │           ├── common
    │           │   ├── footer.html
    │           │   └── header.html
    │           ├── customers.html
    │           ├── index.html
    │           ├── productform.html
    │           ├── products.html
    │           └── productshow.html
    └── test
        ├── java
        ├── kotlin
        └── resources

30 directories, 35 files



Step5. 写Controller

package jason.chen.mini_springboot.restful.controller

import jason.chen.mini_springboot.restful.biz.CustomerService
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.ResponseBody

@Controller
class CustomerController(val customerService: CustomerService) {

    @GetMapping(value = "/")
    fun index(): String {
        return "index"
    }

    @GetMapping("/customers.do")
    fun listAll(model: Model): String {
        val allCustomers = customerService.findAll()
        model.addAttribute("customers", allCustomers)
        return "customers"
    }

    @GetMapping("/listCustomers")
    @ResponseBody
    fun listCustomers(model: Model) = customerService.findAll()

    @GetMapping("/{lastName}")
    @ResponseBody
    fun findByLastName(@PathVariable lastName: String)
            = customerService.findByLastName(lastName)
}

Step6.运行测试

运行./gradlew bootRun, 启动完毕后,访问http://127.0.0.1:9891/customers.do
效果如下

螢幕快照 2017-03-11 22.23.13.png

本章节工程源码:

https://github.com/MiniSpringBootTutorial/mini_springboot/tree/use_thymeleaf_2017.3.11

Kotlin 是一个基于 JVM 的新的编程语言,由 JetBrains 开发。
Kotlin可以编译成Java字节码,也可以编译成JavaScript,方便在没有JVM的设备上运行。
JetBrains,作为目前广受欢迎的Java IDE IntelliJ 的提供商,在 Apache 许可下已经开源其Kotlin 编程语言。

Kotlin学习极佳教程:

http://try.kotlinlang.org/#/Examples/Hello,%20world!/Simplest%20version/Simplest%20version.kt

kotlin极简教程:

http://www.jianshu.com/c/498ebcfd27ad

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
10天前
|
编解码 前端开发 JavaScript
构建高效响应式Web界面:现代前端框架的比较
【4月更文挑战第9天】在移动设备和多样屏幕尺寸盛行的时代,构建能够适应不同视口的响应式Web界面变得至关重要。本文深入探讨了几种流行的前端框架——Bootstrap、Foundation和Tailwind CSS,分析它们在创建响应式设计中的优势与局限。通过对比这些框架的栅格系统、组件库和定制化能力,开发者可以更好地理解如何选择合适的工具来优化前端开发流程,并最终实现高性能、跨平台兼容的用户界面。
|
11天前
|
前端开发 JavaScript 关系型数据库
从前端到后端:构建现代化Web应用的技术探索
在当今互联网时代,Web应用的开发已成为了各行各业不可或缺的一部分。从前端到后端,这篇文章将带你深入探索如何构建现代化的Web应用。我们将介绍多种技术,包括前端开发、后端开发以及各种编程语言(如Java、Python、C、PHP、Go)和数据库,帮助你了解如何利用这些技术构建出高效、安全和可扩展的Web应用。
|
16天前
|
移动开发 Java Android开发
构建高效Android应用:探究Kotlin与Java的性能差异
【4月更文挑战第3天】在移动开发领域,性能优化一直是开发者关注的焦点。随着Kotlin的兴起,其在Android开发中的地位逐渐上升,但关于其与Java在性能方面的对比,尚无明确共识。本文通过深入分析并结合实际测试数据,探讨了Kotlin与Java在Android平台上的性能表现,揭示了在不同场景下两者的差异及其对应用性能的潜在影响,为开发者在选择编程语言时提供参考依据。
|
17天前
|
数据库 Android开发 开发者
构建高效Android应用:Kotlin协程的实践指南
【4月更文挑战第2天】随着移动应用开发的不断进步,开发者们寻求更流畅、高效的用户体验。在Android平台上,Kotlin语言凭借其简洁性和功能性赢得了开发社区的广泛支持。特别是Kotlin协程,作为一种轻量级的并发处理方案,使得异步编程变得更加简单和直观。本文将深入探讨Kotlin协程的核心概念、使用场景以及如何将其应用于Android开发中,以提高应用性能和响应能力。通过实际案例分析,我们将展示协程如何简化复杂任务,优化资源管理,并为最终用户提供更加流畅的体验。
|
1天前
|
JSON Java fastjson
Spring Boot 底层级探索系列 04 - Web 开发(2)
Spring Boot 底层级探索系列 04 - Web 开发(2)
13 0
|
2天前
|
移动开发 Android开发 开发者
构建高效Android应用:采用Kotlin进行内存优化的策略
【4月更文挑战第18天】 在移动开发领域,性能优化一直是开发者关注的焦点。特别是对于Android应用而言,由于设备和版本的多样性,确保应用流畅运行且占用资源少是一大挑战。本文将探讨使用Kotlin语言开发Android应用时,如何通过内存优化来提升应用性能。我们将从减少不必要的对象创建、合理使用数据结构、避免内存泄漏等方面入手,提供实用的代码示例和最佳实践,帮助开发者构建更加高效的Android应用。
5 0
|
5天前
|
数据库 开发者 Python
Python中使用Flask构建简单Web应用的例子
【4月更文挑战第15天】Flask是一个轻量级的Python Web框架,它允许开发者快速搭建Web应用,同时保持代码的简洁和清晰。下面,我们将通过一个简单的例子来展示如何在Python中使用Flask创建一个基本的Web应用。
|
8天前
|
JavaScript 前端开发 API
Vue.js:构建高效且灵活的Web应用的利器
Vue.js:构建高效且灵活的Web应用的利器
|
12天前
|
移动开发 API Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【4月更文挑战第7天】 在移动开发领域,性能优化和应用响应性的提升一直是开发者追求的目标。近年来,Kotlin语言因其简洁性和功能性在Android社区中受到青睐,特别是其对协程(Coroutines)的支持,为编写异步代码和处理并发任务提供了一种更加优雅的解决方案。本文将探讨Kotlin协程在Android开发中的应用,揭示其在提高应用性能和简化代码结构方面的潜在优势,并展示如何在实际项目中实现和优化协程。
|
16天前
|
编解码 前端开发 开发者
构建响应式Web界面:Flexbox与Grid布局的深度对比
【4月更文挑战第4天】 在现代前端开发中,构建灵活且响应式的用户界面是至关重要的。随着移动设备浏览量的增加,能够适应不同屏幕尺寸和分辨率的布局技术变得必不可少。Flexbox和Grid是CSS提供的两种强大的布局机制,它们各自以独特的方式解决了响应式设计的挑战。本文将深入探讨Flexbox和Grid的核心概念、使用场景和性能考量,为开发者提供在面对不同布局需求时做出明智选择的依据。