发表更新2 分钟读完 (大约295个字)
Vertx基础
响应json, 需要安装jackson
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.4</version> </dependency>
router .get("/some/path") .respond( ctx -> Future.succeededFuture(new Pojo()));
或者 ctx.json(new Todo());
|
使用阻塞式处理器
1 2 3 4 5 6
| router.route().blockingHandler(ctx -> { service.doSomethingThatBlocks(); ctx.next(); });
|
精确路由
1 2 3 4 5 6 7 8 9
| Route route = router.route().path("/some/path/"); 会匹配
Route route2 = router.route().path("/some/path"); 会匹配
|
路径参数
1
| ctx.pathParam("productType");
|
重定向
1
| ctx.redirect("https://wwww.baidu.com");
|
重定向到某个路由上去
1
| ctx.reroute("/some/path/B")
|
错误处理
1 2 3 4 5 6 7 8 9
| Route route = router.route("/*"); route.failureHandler(failureRoutingContext -> { int statusCode = failureRoutingContext.statusCode(); HttpServerResponse response = failureRoutingContext.response(); response.setStatusCode(statusCode).end("Sorry! Not today");
});
|
使用session
1 2 3 4 5 6 7 8 9 10 11
| SessionStore store = LocalSessionStore.create(vertx); SessionHandler sessionHandler = SessionHandler.create(store);
router.route().handler(sessionHandler);
router.route("/somepath/blah/").handler(ctx -> { Session session = ctx.session(); session.put("foo", "bar");
});
|
静态文件
1 2 3
| router.route("/static/*").handler(StaticHandler.create()); 将访问的是 resources/webroot下的文件
|