簡體   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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM