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")
// 这个处理器将保证这个Pojo会被序列化成json
// content type被设置成 "application/json"
.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/");
会匹配
// `/some/path/`
// `/some/path//`
Route route2 = router.route().path("/some/path");
会匹配
// `/some/path`
// `/some/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();
// RuntimeException的状态码将为500
// 或403,表示其他失败
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);
// 确保所有请求都可以路由经过这个session处理器
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下的文件
作者

建指所向

发布于

2022-10-10

更新于

2023-11-07

许可协议