0

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.

2
  • 1
    Use something like Thymeleaf. It does pretty much what you are looking for. Commented Feb 2, 2023 at 23:07
  • I should add that I want to implement the mechanism myself, I'm not looking for a tool that does everything for me. But thanks anyway! Commented Feb 3, 2023 at 14:29

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

How would I make this more dynamic so that the tpl depends on what's in the url?
You read it with something like request.getPathInfo()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.