Home > OS >  Process html with java servlet
Process html with java servlet

Time:02-03

I have an html template file, lets call it index.tpl, which I want to process with a java servlet. This is what index.tpl looks like:

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

How can I make a servlet that takes this html as an input, processes it, and sends it back to the browser?

The user journey is basically:

1.User types something like webAppDomain.com/index.tpl?id=1

2.Servlet processes index.tpl and shows the filled template to the user

I'm specifically interested in knowing how the servlet can take the html code as an input to process.

I've tried searching for some way to do this, but I've literally just picked up servlets and I'm a bit lost.

CodePudding user response:

you can try this by using Velocity

add Velocity dependency put this in your 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();

set content for response

response.setContentType("text/html");
response.getWriter().write(result);

CodePudding user response:

In your servlet code for the servlet at "/", in the doGet() method read the path to find your template file:

   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();
}
  • Related