新建项目
注意选择模版
Pom.xml中添加依赖
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>3.5.4</version>
</dependency>
添加代码
打开Hello.kt,添加以下代码
import io.vertx.core.Vertx
import io.vertx.core.json.Json
import io.vertx.ext.web.Router
class Hello {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val vertx = Vertx.vertx()
val httpServer = vertx.createHttpServer()
val router = Router.router(vertx)
router.get("/").handler { routingContext ->
val response = routingContext.response()
response.putHeader("content-type", "text/plain")
.setChunked(true)
.write("Hi Lianglianglee")
.end("Ended")
}
router.get("/json/:name").handler { routingContext ->
val request = routingContext.request()
var name = request.getParam("name")
val response = routingContext.response()
response.putHeader("content-type", "application/json")
.setChunked(true)
.write(Json.encodePrettily(ResponseObj(name)))
.end()
}
router.get("/json").handler { routingContext ->
val response = routingContext.response()
response.putHeader("content-type", "application/json")
.setChunked(true)
.write(Json.encodePrettily(ResponseObj("Lianglianglee")))
.end()
}
httpServer.requestHandler(router::accept).listen(8087)
}
}
data class ResponseObj(var name: String = "")
}
该程序拥有三个router
/
/json
/json/:name
其中/json/:name是restful接口
运行
运行后,在浏览器中分别输入:
localhost:8087/
localhost:8087/json
localhost:8087/json/Demo
可以看到: