跳到主要内容

模板引擎整合

在这个例子中,我们将在ActiveJ应用程序中实现模板引擎。 这个例子显示了如何创建一个简单的民意调查应用,该应用可以创建带有自定义标题、描述和选项的新民意调查。 每个新的投票都会有一个独特的生成链接,引导你到可以投票的页面。

请参阅使用 ActiveJ实现这些功能的简单程度:嵌入的应用程序服务器仅有大约 100 行代码 没有额外的 xml 配置。 在这个例子中,我们使用 Mustache 作为模板引擎。

这里我们只考虑 ApplicationLauncher,它是应用程序的主类。 你可以在以下网站找到完整的例子来源 GitHub

创建发射器

ApplicationLauncher 启动我们的应用程序,负责路由和HTML页面上的适当内容生成。 我们将扩展ActiveJ的 HttpServerLauncher 来管理应用程序的生命周期。

note

在这个例子中,我们省略了对错误的处理,以保持一切的简短和简单。

public final class ApplicationLauncher extends HttpServerLauncher {
  private static ByteBuf applyTemplate(Mustache mustache, Map<String, Object> scopes) {    ByteBufWriter writer = new ByteBufWriter();    mustache.execute(writer, scopes);    return writer.getBuf();  }
  @Provides  PollDao pollRepo() {    return new PollDaoImpl();  }

让我们仔细看看这个发射器。 它包含两种方法。

  • applyTemplate(Mustache mustache, Map<String, Object> scopes) 通过一个 ByteBuf - 一个更有效的ByteBuffer的实现,将提供的Mustache模板填入给定的数据。
  • pollRepo() 提供了我们应用程序的业务逻辑。 @Provides 注解意味着它是通过 ActiveJ Inject DI。 接下来,我们提供 AsyncServlet
public final class ApplicationLauncher extends HttpServerLauncher {
  private static ByteBuf applyTemplate(Mustache mustache, Map<String, Object> scopes) {    ByteBufWriter writer = new ByteBufWriter();    mustache.execute(writer, scopes);    return writer.getBuf();  }
  @Provides  PollDao pollRepo() {    return new PollDaoImpl();  }

AsyncServlet ,我们创建了三个Mustache对象,每个HTML页面一个。 为了定义路由,我们创建了一个 RoutingServlet。 你可能会注意到,这种路由方式类似于Express.js。 在上面的例子中 ,我们已经通过使用 map 方法将映射添加到主页上。 方法map(@Nullable HttpMethod method, String path, AsyncServlet servlet) 添加一个路由到 RoutingServlet: method 是HTTP方法之一 (GET, POST 等等) path 是服务器上的路径 servlet 定义了请求处理的逻辑。 如果您需要从 请求 获取一些数据,您可以使用: 请求。 etPathParameter(密钥)/请求。 etQueryParameter(密钥) (见 查询参数用法') 提供所需参数的密钥并收到相应的字符串 请求。 etPostParameters() 获取所有请求参数的地图 在这个请求中,我们获得所有当前的民意调查和有关信息,以便生成 listPolls*。 让我们再增加一个要求。

public final class ApplicationLauncher extends HttpServerLauncher {
  private static ByteBuf applyTemplate(Mustache mustache, Map<String, Object> scopes) {    ByteBufWriter writer = new ByteBufWriter();    mustache.execute(writer, scopes);    return writer.getBuf();  }
  @Provides  PollDao pollRepo() {    return new PollDaoImpl();  }

该请求返回一个有投票的页面,该投票的ID在路径中被指定。 注意提供的路径 /poll/:id 语法。 : 说明以下字符直到下一个 / 是一个 变量;在这种情况下,其关键词是 id。 这样,你就不必把每个投票的ID映射到不同的请求。 接下来, /create, /vote, /add/delete 路径的请求分别负责提供创建 新投票、投票、将创建的投票添加到 pollDao 以及从其中删除投票的页面。

.map(GET, "/create", request ->    HttpResponse.ok200()        .withBody(applyTemplate(singlePollCreate, emptyMap()))).map(POST, "/vote", request -> request.loadBody()    .then(() -> {      Map<String, String> params = request.getPostParameters();      String option = params.get("option");      String stringId = params.get("id");      if (option == null || stringId == null) {        return Promise.of(HttpResponse.ofCode(401));      }
      int id = Integer.parseInt(stringId);      PollDao.Poll question = pollDao.find(id);
      question.vote(option);
      return Promise.of(HttpResponse.redirect302(nonNullElse(request.getHeader(REFERER), "/")));    })).map(POST, "/add", request -> request.loadBody()    .map($ -> {      Map<String, String> params = request.getPostParameters();      String title = params.get("title");      String message = params.get("message");
      String option1 = params.get("option1");      String option2 = params.get("option2");
      int id = pollDao.add(new PollDao.Poll(title, message, listOf(option1, option2)));      return HttpResponse.redirect302("poll/" + id);    })).map(POST, "/delete", request -> request.loadBody()    .then(() -> {      Map<String, String> params = request.getPostParameters();      String id = params.get("id");      if (id == null) {        return Promise.of(HttpResponse.ofCode(401));      }      pollDao.remove(Integer.parseInt(id));
      return Promise.of(HttpResponse.redirect302("/"));    }));

另外,我们定义了 main() 方法,它将启动我们的启动器。

public static void main(String[] args) throws Exception {  Launcher launcher = new ApplicationLauncher();  launcher.launch(args);}

就这样,我们有了一个全功能的民意调查应用程序!

运行应用程序

如果你想运行这个例子,你需要从GitHub上导入 ,将其作为一个Maven项目。 查阅分支机构 v5.5。 在运行这个例子之前,构建项目(Ctrl F9 for IntelliJ IDEA)。 打开 ApplicationLauncher 类并运行其 main() 方法。 然后打开你喜欢的浏览器,进入 localhost:8080