在vert.x中使用Thymeleaf模板,需要引入vertx-web-templ-thymeleaf依赖。pom.xml文件如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javafm</groupId> <artifactId>vertx.helloworld</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web-templ-thymeleaf</artifactId> <version>3.3.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
同前面一篇文章一样,不需要引入core和web了,vertx-web-templ-thymeleaf会自动导入相关依赖。
编写模板文件resources/templates/hello.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1 th:text="${msg}"></h1> </body> </html>
编写vertx http服务,并解析模板,HelloThymeleaf.java
package com.javafm.vertx.helloworld; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.ext.web.Router; import io.vertx.ext.web.templ.ThymeleafTemplateEngine; /** * Created by lemontea <36634584@qq.com> on 16-12-19. */ public class HelloThymeleaf { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); HttpServer httpServer = vertx.createHttpServer(); Router router = Router.router(vertx); // 创建一个模板引擎 ThymeleafTemplateEngine templateEngine = ThymeleafTemplateEngine.create(); // 设置访问路径 router.route("/hello").handler(routingContext -> { // 传递值到模板中,在模板中可以通过${msg}直接取出 routingContext.put("msg", "Hello Thymeleaf!"); // 渲染模板 templateEngine.render(routingContext, "templates/hello.html", res -> { // 如果模板解析成功,就将结果写到response if (res.succeeded()) { routingContext.response().putHeader("Content-Type", "text/html").end(res.result()); } else { // 如果解析失败,就显示fail routingContext.fail(res.cause()); } }); }); httpServer.requestHandler(router::accept).listen(8080); } }
启动http服务,到浏览器查看结果
原创文章,转载请注明出处。