繁体   English   中英

使用 java servlet 处理 html

[英]Process html with java servlet

提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文

我有一个 html 模板文件,我们称它为 index.tpl,我想用 java servlet 处理它。 这是 index.tpl 的样子:

<html>
  <body>
    <h1> Pet profile - {pet.name} </h1>
    <p> age {pet.age} </p>
    etc.
  </body>
</html>

我怎样才能制作一个 servlet,将这个 html 作为输入,对其进行处理,然后将其发送回浏览器?

用户旅程基本上是:

1.用户键入类似 webAppDomain.com/index.tpl?id=1 的内容

2.Servlet处理index.tpl,将填写好的模板展示给用户

我特别想知道 servlet 如何将 html 代码作为输入进行处理。

我试过寻找某种方法来做到这一点,但我实际上只是拿起了 servlets,我有点迷路了。

在“/”处的 servlet 的 servlet 代码中,在 doGet() 方法中读取路径以找到您的模板文件:

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

   String pathFromUrl = request.getPathInfo();

   String filePath = BASE_PATH + "/" + pathFromUrl;
   
   byte[] bytes = Files.readAllBytes(Paths.get(filePath));
   String fileContent = new String (bytes);

   String id = request.getParameterByName("id");

   Pet pet = // get pet with id

   // TODO modify fileContent with pet content

   response.setStatus(HttpServletResponse.SC_OK);
   response.getWriter().write(fileContent);
   response.getWriter().flush();
}

你可以使用 Velocity 试试这个

添加 Velocity 依赖项,将其放入您的 index.tpl

String templateFile = "index.tpl";
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
Template template = velocityEngine.getTemplate(templateFile);
    
VelocityContext context = new VelocityContext();
context.put("pet.name", "Fluffy");
context.put("pet.age", 5);
    
StringWriter writer = new StringWriter();
template.merge(context, writer);
String result = writer.toString();

设置响应内容

response.setContentType("text/html");
response.getWriter().write(result);
问题未解决?试试搜索: 使用 java servlet 处理 html
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM