2.6.2、页面渲染处理程序
此处理程序处理HTTP GET请求以使Wiki页面呈现, 如:
该页面还提供了一个按钮来以Markdown形式编辑页面中的内容。 对于页面和编两个页面我们不建立单独的处理程序和模板, 我们只需依靠JavaScript和CSS在点击按钮时打开和关闭编辑器:
pageRenderingHandler方法代码如下:
private static final String EMPTY_PAGE_MARKDOWN =
"# A new page\n" +
"\n" +
"Feel-free to write in Markdown!\n";
private void pageRenderingHandler(RoutingContext context) {
String page = context.request().getParam("page"); (1)
dbClient.getConnection(car -> {
if (car.succeeded()) {
SQLConnection connection = car.result();
connection.queryWithParams(SQL_GET_PAGE, new JsonArray().add(page), fetch -> { (2)
connection.close();
if (fetch.succeeded()) {
JsonArray row = fetch.result().getResults()
.stream()
.findFirst()
.orElseGet(() -> new JsonArray().add(-1).add(EMPTY_PAGE_MARKDOWN));
Integer id = row.getInteger(0);
String rawContent = row.getString(1);
context.put("title", page);
context.put("id", id);
context.put("newPage", fetch.result().getResults().size() == 0 ? "yes" : "no");
context.put("rawContent", rawContent);
context.put("content", Processor.process(rawContent)); (3)
context.put("timestamp", new Date().toString());
templateEngine.render(context, "templates", "/page.ftl", ar -> {
if (ar.succeeded()) {
context.response().putHeader("Content-Type", "text/html");
context.response().end(ar.result());
} else {
context.fail(ar.cause());
}
});
} else {
context.fail(fetch.cause());
}
});
} else {
context.fail(car.cause());
}
});
}
- 可以通过上下文请求对象访问URL参数(/wiki/:name);
- 将参数值传递给SQL查询是使用JsonArray完成的,其中元素的顺序对应SQL查询中的?符号的顺序;
- Proccessor类来自我们使用的txtmark Markdown渲染库。
page.ftl的FreeMarker模板代码如下: