Isenção de responsabilidadeO autor não é um programador, não pode codificar
Não sou um guru ou especialista legal em Kotlin, nem no Spring, nem em nenhuma outra tecnologia usada neste artigo. Eu sou um java java regular que decidiu experimentar o kotlin. Tudo é feito no Sapsan no joelho na estrada com o trem de tecnologia
Para quem
Para desenvolvedores java que acabaram de ouvir falar do kotlin, mas ainda não o tocaram
Para que
Para mostrar que o kotlin funciona bem com boot de mola, e em combinação com o DSL em termos de trabalho com html, será mais conveniente do que a abordagem clássica com jsp.
Configuração para inicialização por mola
Aqui, tudo não é muito diferente de java
- Criar projeto (kotlin)
- Adicione o repositório jcenter, dependência do kotlin-stdlib e spring-boot-starter-web, plugin kotlin-maven-plugin
- Certifique-se de criar um pacote para funcionar, caso contrário, a primavera cairá
- Crie uma classe Application aberta
- No aplicativo, adicione o método principal com a linha runApplication <Application> (* args)
- Adicione um controlador HelloWorld que retornará uma saudação ao mundo
Códigopom.xml<?xml version="1.0" encoding="UTF-8"?> <project xmlns="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>
Aulas package example import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication open class Application fun main(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 @Controller class HelloWorld{ @RequestMapping("/") @ResponseBody fun mainPage(): String { return " " } }
Adicionar kotlinx.html
O Kotlin possui uma extensão na forma de DSL para um trabalho conveniente com html. Ele permite que você misture a abordagem declarativa do html com a abordagem imperativa de uma linguagem comum.
table {// thead{ tr { td { +"" //+ } td { +"" } } } for (person in PersonGenerator().generate()) { // for kotlin tr { td { +person.name } td { text(person.age) // "+" String } } } }
Esse código formará uma página html na qual haverá uma placa com os nomes das pessoas e sua idade
Códigopom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="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>
Aulas package example data class Person(val name: String,var age: Int)
package example import java.util.* import kotlin.collections.ArrayList class PersonGenerator{ private val nameList = arrayOf("", "", "", "", "", ""); fun generate(): List<Person> { val random = Random() val personList = ArrayList<Person>() for (i in 1..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 @Controller class HelloWorld { @RequestMapping("/") @ResponseBody fun mainPage(): 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) } } } } } } } }
Adicionar css
O Kotlinx.html praticamente não sabe trabalhar com css, com ele você pode adicionar um link a um estilo pronto ou inserir o seu próprio usando inseguro. Tudo se torna muito melhor se você adicionar Aza-Kotlin-CSS - DSL adicionando trabalho com 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" } }
Trabalhar com js também passa por inseguros
Sumário
Na minha opinião, escrever a exibição no DSL é mais conveniente do que no JSP. Não preciso primeiro entrar no banco de dados, colocar o resultado do cálculo em um objeto intermediário, que retirarei em jsp. Posso preencher imediatamente meu jsp a partir da base de código do projeto, ignorando a camada de abstração de que não preciso. Infelizmente, usei jsp apenas no meu projeto de estimação e não lido com a frente. Eu estaria interessado em ler a opinião de profissionais sobre esse assunto.
Links úteis
Um exemplo de rótulo rosa desenvolvido em um artigo
Documentação Kotlin
Documentação conectando a bota de mola ao kotlin
Documentação do Kotlinx.html
Documentação Aza-Kotlin-CSS