一直觉得java开发太重了,想找一个轻量、靠谱的框架来完成一些个人的小项目,之前一直在关注vert.x,最近看他更新到了5.0.0.CR3版,简单入门一波。Vert.x 是一系列工具包,它可以在Java虚拟机上运行的响应式、非阻塞的异步应用程序,它涵盖了多个不同的组件,用于创建具有大量消息、大型事件处理、HTTP 交互等的应用程序。
如果你是idea Ultimate 版本,你可以直接在idea中创建vertx项目;如果你是vscode,可以下载vscode-vertx-starter插件来创建vertx项目;亦或者在vertx官网创建项目。之类我们只是简单介绍web开发,所以只选择Vert.x Web依赖就可以了。简单改下MainVerticle
public class MainVerticle extends VerticleBase {
@Override
public Future<?> start() {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route().handler(ctx -> {
HttpServerResponse response = ctx.response();
response.putHeader("content-type", "text/plain");
response.end("Hello World from Vert.x-Web!");
});
return server.requestHandler(router).listen(8080);
}
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(MainVerticle.class.getName());
}
}
使用router.route指定匹配的路径,使用使用route.handler指定该路径的处理方法
router.route("/some/path").handler(ctx -> {
HttpServerResponse response = ctx.response();
response.end("route1\n");
});
值得注意的是:同一个路径可以有多个处理方法,可以使用ctx.next()
来进入下一个处理方法。
通过:name指定pathParam,并通过ctx.pathParam来获取对应名称参数的值。
访问 /user/123 会返回userId is: 123
router.route("/user/:userId").handler(ctx -> {
String userId = ctx.pathParam("userId");
HttpServerResponse response = ctx.response();
String resStr = String.format("userId is: %s", userId);
response.end(resStr);
});
通过request.getParam可以获取请求中?
中的查询参数
访问 /query?username=tom 会返回 username is: tom
,如果没有username的参数,则会返回username is: null
router.route("/query").handler(ctx -> {
String username = ctx.request().getParam("username");
HttpServerResponse response = ctx.response();
String resStr = String.format("username is: %s", username);
response.end(resStr);
});
要在vertx中获取request body参数,需要先加入下面这句话。
router.route().handler(BodyHandler.create());
然后可以通过bodyHandler来获取body的内容。请求/save接口时body参数和返回结果一致:
{
"name": "tom",
"age": 22
}
代码如下:
router.post("/save").handler(ctx -> {
ctx.request().bodyHandler(buffer -> {
JsonObject jsonObject = buffer.toJsonObject();
ctx.json(jsonObject);
});
});
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。