今天我们尝试Kotlin整合Vertx,并决定建立一个非常简单的Web应用程序,使用Kotlin和Vertx作为编程语言进行编码构建。

生成项目

打开控制台窗口执行以下代码进行生成一个maven项目

mvn archetype:generate -DgroupId=com.edurt.kvi -DartifactId=kotlin-vertx-integration -DarchetypeArtifactId=maven-archetype-quickstart -Dversion=1.0.0 -DinteractiveMode=false

修改pom.xml增加java和kotlin的支持

<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/maven-v4_0_0.xsd">

 <modelVersion>4.0.0</modelVersion>
 <groupId>com.edurt.kvi</groupId>
 <artifactId>kotlin-vertx-integration</artifactId>
 <packaging>jar</packaging>
 <version>1.0.0</version>

 <name>kotlin-vertx-integration</name>
 <description>Kotlin Vertx Integration is a open source kotlin vertx integration example.</description>

 <!-- properties -->
 <properties>
  <!-- dependency -->
  <dependency.kotlin.version>1.2.71</dependency.kotlin.version>
  <dependency.vertx.ersion>3.4.1</dependency.vertx.ersion>
  <!-- plugin -->
  <plugin.maven.compiler.version>3.3</plugin.maven.compiler.version>
  <plugin.maven.javadoc.version>2.10.4</plugin.maven.javadoc.version>
  <plugin.maven.kotlin.version>1.2.71</plugin.maven.kotlin.version>
  <!-- environment -->
  <environment.compile.java.version>1.8</environment.compile.java.version>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
  <jvmTarget>1.8</jvmTarget>
 </properties>

 <!-- dependencys -->
 <dependencies>
  <!-- kotlin -->
  <dependency>
   <groupId>org.jetbrains.kotlin</groupId>
   <artifactId>kotlin-stdlib-jdk8</artifactId>
   <version>${dependency.kotlin.version}</version>
  </dependency>
  <dependency>
   <groupId>org.jetbrains.kotlin</groupId>
   <artifactId>kotlin-reflect</artifactId>
   <version>${dependency.kotlin.version}</version>
  </dependency>
  <!-- vertx -->
  <dependency>
   <groupId>io.vertx</groupId>
   <artifactId>vertx-core</artifactId>
   <version>${dependency.vertx.ersion}</version>
  </dependency>
  <dependency>
   <groupId>io.vertx</groupId>
   <artifactId>vertx-web</artifactId>
   <version>${dependency.vertx.ersion}</version>
  </dependency>
 </dependencies>

 <!-- prerequisites -->
 <prerequisites>
  <maven>3.5.0</maven>
 </prerequisites>

 <!-- build -->
 <build>
  <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
  <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
  <plugins>
   <plugin>
    <artifactId>kotlin-maven-plugin</artifactId>
    <groupId>org.jetbrains.kotlin</groupId>
    <configuration>
     <args>
      <arg>-Xjsr305=strict</arg>
     </args>
     <compilerPlugins>
      <plugin>spring</plugin>
      <plugin>jpa</plugin>
      <plugin>all-open</plugin>
     </compilerPlugins>
     <pluginOptions>
      <option>all-open:annotation=javax.persistence.Entity</option>
     </pluginOptions>
    </configuration>
    <dependencies>
     <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-maven-allopen</artifactId>
      <version>${plugin.maven.kotlin.version}</version>
     </dependency>
     <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-maven-noarg</artifactId>
      <version>${plugin.maven.kotlin.version}</version>
     </dependency>
    </dependencies>
    <executions>
     <execution>
      <id>kapt</id>
      <goals>
       <goal>kapt</goal>
      </goals>
      <configuration>
       <sourceDirs>
        <sourceDir>src/main/kotlin</sourceDir>
       </sourceDirs>
       <annotationProcessorPaths>
        <annotationProcessorPath>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-configuration-processor</artifactId>
         <version>${project.parent.version}</version>
        </annotationProcessorPath>
       </annotationProcessorPaths>
      </configuration>
     </execution>
    </executions>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${plugin.maven.compiler.version}</version>
    <configuration>
     <source>${environment.compile.java.version}</source>
     <target>${environment.compile.java.version}</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>${plugin.maven.javadoc.version}</version>
    <configuration>
     <aggregate>true</aggregate>
     <!-- custom tags -->
     <tags>
      <tag>
       <name>Description</name>
       <placement>test</placement>
       <head>description</head>
      </tag>
     </tags>
     <!-- close jdoclint check document -->
     <additionalparam>-Xdoclint:none</additionalparam>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>

添加Vertx实例

创建CoreVerticle类文件

package com.edurt.kvi.core

import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.core.Handler
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext

class CoreVerticle : AbstractVerticle() {

 override fun start(startFuture: Future<Void>?) {
  val router = createRouter()
  val port = config().getInteger("http.port", 8080)
  vertx.createHttpServer()
    .requestHandler { router.accept(it) }
    .listen(port) { result ->
     if (result.succeeded()) {
      startFuture?.complete()
     } else {
      startFuture?.fail(result.cause())
     }
    }
 }

 private fun createRouter() = Router.router(vertx).apply {
  get("/").handler(handlerRoot)
 }

 /**
  * create router instance
  */
 val handlerRoot = Handler<RoutingContext> { req ->
  req.response().end("Hello Kotlin Vertx Integration!")
 }

}

设置启动类

package com.edurt.kvi

import com.edurt.kvi.core.CoreVerticle
import io.vertx.core.Vertx

class KotlinVertxIntegration

fun main(args: Array<String>) {
 val vertx = Vertx.vertx()
 vertx.deployVerticle(CoreVerticle::class.java.name)
}

以上操作在vertx.deployVerticle阶段执行了部署Verticle的操作,即部署CoreVerticle。

启动应用后浏览器访问http://localhost:8080出现以下页面

增加页面渲染功能

修改pom.xml文件增加页面依赖

<dependency.slf4j.version>1.7.25</dependency.slf4j.version>

<dependency>
 <groupId>io.vertx</groupId>
 <artifactId>vertx-web-templ-thymeleaf</artifactId>
 <version>${dependency.vertx.ersion}</version>
</dependency>
<dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-log4j12</artifactId>
 <version>${dependency.slf4j.version}</version>
</dependency>

增加页面渲染文件

package com.edurt.kvi.router

import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.templ.ThymeleafTemplateEngine
import org.thymeleaf.templatemode.TemplateMode

class HomeViewRouter

fun index(r: Router) {
 val engine = ThymeleafTemplateEngine.create().setMode(TemplateMode.HTML)
 r.get("/index.html").handler { c ->
  render(c, engine, "templates/index.html")
 }
}

fun render(c: RoutingContext, engine: ThymeleafTemplateEngine, templ: String) {
 engine.render(c, templ) { res ->
  if (res.succeeded()) {
   c.response().end(res.result())
  } else {
   c.fail(res.cause())
  }
 }
}

在templates/index.html目录下创建页面文件

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Kotlin Vertx Integration</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>

<body>
<p>Welcome To Kotlin Vertx Integration!</p>
</body>
</html>

修改CoreVerticle增加页面跳转

package com.edurt.kvi.core

import com.edurt.kvi.router.index
import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.core.Handler
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerResponse
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext

class CoreVerticle : AbstractVerticle() {

 override fun start() {
  val router = createRouter(vertx)

  // go to index page
  index(router)

  vertx.createHttpServer().requestHandler { handler -> router.accept(handler) }.listen(8080)

//  val port = config().getInteger("http.port", 8080)
//  vertx.createHttpServer()
//    .requestHandler { router.accept(it) }
//    .listen(port) { result ->
//     if (result.succeeded()) {
//      startFuture?.complete()
//     } else {
//      startFuture?.fail(result.cause())
//     }
//    }
 }

 private fun createRouter() = Router.router(vertx).apply {
  get("/").handler(handlerRoot)
 }

 /**
  * create router instance
  */
 val handlerRoot = Handler<RoutingContext> { req ->
  req.response().end("Hello Kotlin Vertx Integration!")
 }

 fun createRouter(v: Vertx): Router {
  var router = Router.router(v)
  router.route("/").handler { c -> c.response().end("Hello Kotlin Vertx Integration!") }
  router.route("/index").handler { c -> c.response().html().end("Hello Kotlin Vertx Integration Page!") }
  return router
 }

 fun HttpServerResponse.html(): HttpServerResponse {
  return this.putHeader("content-type", "text/html")
 }

}

启动应用后浏览器访问http://localhost:8080/index.html出现以下页面

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持Devmax。

Kotlin整合Vertx开发Web应用的更多相关文章

  1. Kotlin难点解析:extension和this指针

    扩展是Kotlin语言中使用非常简单的一个特性。关于这个问题,其实我之前的一篇文章[[Kotlin]LambdaandExtension](https://www.jianshu.com/p/d7a...中有提到过。为了解决这个问题,官方提出了两个新的概念:dispatchreceiver和extensionreceiver。extensionreceiver:中文翻译为扩展接收者。为了简化,这里我们将dispatchreceiver简称为DR,将extensionreceiver简称为ER。如果你习惯了

  2. android – Kotlin类NoClassDefFoundError崩溃

    我有一个使用以下库的现有Android项目:>Autovalue>Dagger2>RxJava>Retrolambda我正在尝试添加Kotlin支持,以便我可以将项目慢慢迁移到Kotlin.这就是我所做的.>添加了Kotlin依赖.>将其中一个类转换为Kt类并转移到src/main/kotlin/..包中.>在源集中添加了kotlin.sourceSets{main.java.srcDirs=’s

  3. android – Kotlin和Dagger2

    我正在尝试将Kotlin添加到我的项目中,但在启用Kotlin之后我无法构建,因为Dagger2类不再生成.我尝试了第二个项目,我有同样的问题.这些是我为启用Kotlin所做的改变:项目build.gradle:Appbuild.gradle:错误发生在这里:其中不再定义DaggerObjectGraph.任何帮助将不胜感激.解决方法只需删除

  4. android – 在Kotlin中不能使用argb color int值吗?

    当我想在Kotlin中为TextView的textColor设置动画时:发生此错误:似乎在Kotlin中不能将值0xFF8363FF和0xFFC953BE强制转换为Int,但是,它在Java中是正常的:有任何想法吗?提前致谢.解决方法0xFF8363FF是Long,而不是Int.你必须明确地将它们转换为Int:关键是0xFFC953BE的数值是4291384254,因此它应该存储在Long变量中.但这里的高位是符号位,表示负数:-3583042,可以存储在Int中.这就是两种语言之间的区别.在Kotlin

  5. 什么是我可以使用Kotlin的最早的Android API级别?

    我认为这个问题很清楚但是我能在Kotlin上定位的最早API级别是什么?解决方法实际上,任何API级别.这是因为Kotlin被编译为JVM6平台的字节码,所有AndroidAPI级别都支持该字节码.因此,除非您在Kotlin代码中使用任何较新的AndroidAPI,否则它不需要任何特定的API级别.

  6. android – Kotlin数据类和可空类型

    我是Kotlin的新手,我不知道为什么编译器会抱怨这段代码:编译器抱怨测试?.data.length,它说我应该这样做:test?.length.但是数据变量是String,而不是String?,所以我不明白为什么我要把它?当我想检查长度.解决方法表达式test?.data部分可以为空:它是test.data或null.因此,获取其长度并不是零安全的,而是应该再次使用safecalloperator:test?.length.可空性通过整个调用链传播:你必须将这些链写成?.)).e),因为,如果其中一个左

  7. android – Kotlin自定义获取执行方法调用

    像这样的东西:仍在使用Kotlin并且不确定get()方法是否会引用编辑器而不是创建新的编辑器.解决方法第二个属性声明适合您的需要:它有一个customgetter,因此获取属性值将始终执行getter,并且不存储该值.你可能会被等号get()=…

  8. android – Kotlin合成扩展和几个包含相同的布局

    我找了一些这样的:我在Studio中看到我可以访问dayName但是dayNameTextView引用了哪一个?正常,如果我只有一个包含的布局,它工作正常.但现在我有多次包含相同的布局.我当然可以这样做:但我正在寻找好的解决方案.版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  9. android – java.lang.IllegalArgumentException:指定为非null的参数为null:方法kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull

    我收到了这个错误java.lang.IllegalArgumentException:指定为非null的参数为null:方法kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull,参数事件为线覆盖funonEditorAction(v:TextView,actionId:Int,event:KeyEvent)以下是整个代码.这段代码最初是在ja

  10. android – Kotlin:如何访问CustomView的Attrs

    我在Kotlin中创建了一个自定义视图,并希望访问它的属性资源.以下是我的代码请注意,这将在init函数的attrs中出错.我想知道如何进入attrs?

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部