One-page site on Kotlin and SpringBoot without using JSP

  • Tutorial
Disclaimer

The author is not a prog, he does not know how to code.
I am not a guru or a tough specialist either in Kotlin, nor in Spring, nor in any other technology used in this article. I am an ordinary java junior who decided to try kotlin. Everything is done in the "Sapsan" on the knee on the road with techtrain


For whom


For java developers who have only heard about Kotlin, but haven’t touched it yet


For what


Show that kotlin works fine with spring boot, and in combination with DSL in terms of working with html it is more convenient to be more comfortable than the classical approach with jsp.


Configuration for spring boot


Everything is a little different from java


  1. Create project (kotlin)
  2. Add repository jcenter, dependency to kotlin-stdlib and spring-boot-starter-web, plugin kotlin-maven-plugin
  3. Be sure to create a package for work, otherwise Spring will fall
  4. Create open class Application
  5. In the Application add the main method with the line runApplication <Application> (* args)
  6. Add a HelloWorld controller that will return a greeting to the world

Code
pom.xml
<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>habr-sample</artifactId><version>1.0-SNAPSHOT</version><repositories><repository><id>jcenter</id><name>jcenter</name><url>https://jcenter.bintray.com</url></repository></repositories><build><plugins><plugin><groupId>org.jetbrains.kotlin</groupId><artifactId>kotlin-maven-plugin</artifactId><version>RELEASE</version><executions><execution><id>compile</id><phase>compile</phase><goals><goal>compile</goal></goals></execution></executions><configuration><jvmTarget>1.8</jvmTarget></configuration></plugin></plugins></build><dependencies><dependency><groupId>org.jetbrains.kotlin</groupId><artifactId>kotlin-stdlib</artifactId><version>RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>RELEASE</version></dependency></dependencies></project>

Classes
package example
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplicationopenclassApplicationfunmain(args: Array<String>) {
    runApplication<Application>(*args)
}

package example
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
@ControllerclassHelloWorld{
    @RequestMapping("/")@ResponseBodyfunmainPage(): String {
        return"Привет Хабр"
    }
}

Add kotlinx.html


Kotlin has an extension in the form of DSL for convenient work with html. It allows you to mix the declarative html approach with the imperative approach of the usual language.


table {//Объявление тега
    thead{
        tr {
            td {
                +"Имя"//+ добавляет контент в элемент
            }
            td {
                +"Возраст"
            }
        }
    }
    for (person inPersonGenerator().generate()) { //Обычный for из kotlin
        tr {
            td {
                +person.name
            }
            td {
                text(person.age)  //аналог "+" который принимает не только String
            }
        }
    }
}

This code will generate an html page in which there will be a sign with the names of people and their age.


Result


Code
pom.xml
<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>habr-sample</artifactId><version>1.0-SNAPSHOT</version><repositories><repository><id>jcenter</id><name>jcenter</name><url>https://jcenter.bintray.com</url></repository></repositories><build><plugins><plugin><groupId>org.jetbrains.kotlin</groupId><artifactId>kotlin-maven-plugin</artifactId><version>RELEASE</version><executions><execution><id>compile</id><phase>compile</phase><goals><goal>compile</goal></goals></execution></executions><configuration><jvmTarget>1.8</jvmTarget></configuration></plugin></plugins></build><dependencies><dependency><groupId>org.jetbrains.kotlin</groupId><artifactId>kotlin-stdlib-jdk8</artifactId><version>RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>RELEASE</version></dependency><dependency><groupId>org.jetbrains.kotlinx</groupId><artifactId>kotlinx-html-jvm</artifactId><version>RELEASE</version></dependency></dependencies></project>

Classes
package example
dataclassPerson(val name: String,var age: Int)

package example
import java.util.*
import kotlin.collections.ArrayList
classPersonGenerator{
    privateval nameList = arrayOf("Петя", "Вася", "Женя", "Марк", "Иван", "Леопольд");
    fungenerate(): List<Person> {
        val random = Random()
        val personList = ArrayList<Person>()
        for (i in1..15) {
            personList.add(Person(nameList.get(random.nextInt(nameList.size)), random.nextInt(30) + 18))
        }
        return personList;
    }
}

package example
import kotlinx.html.*
import kotlinx.html.stream.createHTML
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
@ControllerclassHelloWorld{
    @RequestMapping("/")@ResponseBodyfunmainPage(): String {
        return createHTML()
                .html {
                    body {
                        table {
                            thead() {
                                tr {
                                    td {
                                        +"Имя"
                                    }
                                    td {
                                        +"Возраст"
                                    }
                                }
                            }
                            val personList= PersonGenerator().generate()
                            for (person in personList ) {
                                tr {
                                    td {
                                        +person.name
                                    }
                                    td {
                                        text(person.age)
                                    }
                                }
                            }
                        }
                    }
                }
    }
}

Add css


Kotlinx.html practically does not know how to work with css, with the help of it you can add a link to an already ready style or insert your own using unsafe. Everything becomes much better if you add Aza-Kotlin-CSS - DSL adding work with css


head {
//Добавить стилей bootstrap
    styleLink("https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css")
    styleLink("https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css")
//Добавление своего стиля
    style("text/css") {
        unsafe {// Заходим в unsafe kotlinx.html
            raw(
                    Stylesheet { // и формируем стиль с Aza-Kotlin-CSS
                        table and td and th {
                            color = 0xFC0Fc0
                        }
                    }.render()
            )
        }
    }
    meta {
        charset = "utf-8"
    }
}

Result


Working with js is also unsafe.


Summary


In my opinion, writing view on DSL is more convenient than on JSP. I do not need to first climb into the base, put the result of the calculation in an intermediate object, which I will later pull out in jsp. I can immediately fill my jsp from the project codebase bypassing the layer of abstraction that I do not need. Unfortunately, I used jsp only in my pet-project and do not do the front at all. I would be interested to read the opinions of professionals on this issue.


useful links


Example of pink
label developed in the article Documentation for the Kotlin
Documentation of connecting spring boot to the Kotlin
Documentation for kotlinx.html
Documentation for Aza-Kotlin-CSS


Also popular now: