Building HTML in Java code only

Does this work for you?

StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append("<html>");
htmlBuilder.append("<head><title>Hello World</title></head>");
htmlBuilder.append("<body><p>Look at my body!</p></body>");
htmlBuilder.append("</html>");
String html = htmlBuilder.toString();

There can be several approaches.

First you can use String, or StringBuilder. This is good for extremely short HTMLs like <html>Hello, <b>world</b></html>.

If HTML is more complicated it is easier to use some API. Take a look on these links:

http://xerces.apache.org/xerces-j/apiDocs/org/apache/html/dom/HTMLBuilder.html

Java HTML Builder (anti-template) library?

or search html builder java in google.

Other possibility is templating. If you actually have a template where you wish to replace a couple of words you can write your HTML as an *.html file with {0}, {} marks for parameters. Then just use java.text.MessageFormat to create actual HTML text.

The next approach is to use "real" template engine like Velocity.


As of Java 13 there is a new feature being added called Text Blocks . To use a Text Block you must use three double quotes AKA """, to open and close the String.

This feature allows us to build something such as html without needing to concatenate Strings, handle new lines, or use a library and build the String very clearly and easily.

Here is a short example of using this new feature for html:

String html = """
              <html>
                  <body>
                      <p>Hello, world</p>
                  </body>
              </html>
              """;

This is equivalent to the below code without using Text Blocks:

String html = "<html>\n" +
              "    <body>\n" +
              "        <p>Hello, world</p>\n" +
              "    </body>\n" +
              "</html>\n";

Source: JEP 355: Text Blocks