6

What is the simplest, fastest way to create a String object (I suppose) that contains HTML (with correct encoding), which I can return for example in @ResponseBody (Spring MVC) ?

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
marioosh
  • 27,328
  • 49
  • 143
  • 192
  • Depends on from what you are creating that HTML but, from what you have mentioned in your question i will say StringBuilder! – Shaunak Jul 28 '11 at 08:40
  • This [SO answer](https://stackoverflow.com/a/45713037/8429746) must be helpful. – RRadley Sep 18 '17 at 11:47

5 Answers5

7

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.

Lefteris008
  • 899
  • 3
  • 10
  • 29
AlexR
  • 114,158
  • 16
  • 130
  • 208
6

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();
rossum
  • 15,344
  • 1
  • 24
  • 38
Alvin
  • 10,308
  • 8
  • 37
  • 49
  • when you say encoding, do you mean UTF-8 etc? or the ">" thing? – Alvin Jul 28 '11 at 09:18
  • Yes, UTF-8. I say about something like that `htmlBuilder.append("Hello Łódź");` – marioosh Jul 28 '11 at 10:09
  • 1
    Java use UTF-8 encoding internally, so whatever you type in Java is in UTF-8 encoding already. Does that answer your question? – Alvin Jul 28 '11 at 10:17
  • 3
    If you know that the String will be longer than sixteen characters, better allocate a large initial buffer: `new StringBuilder(1000)` – Thilo Jul 28 '11 at 10:31
  • Just for completion, values of attributes can be incorporated using String.format, i.e: htmlBuilder.append(String.format("", value, label)); – Hans Poo Jun 14 '17 at 18:01
2

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

Nexevis
  • 4,647
  • 3
  • 13
  • 22
1

Using jsoup or wffweb will be the simplest way to build HTML from Java code. You can dynamically generate HTML using it.

Eg for jsoup:

Document doc = Jsoup.parse("<html></html>");
doc.body().addClass("body-styles-cls");
doc.body().appendElement("div");
System.out.println(doc.toString());

will print

<html>
 <head></head>
 <body class=" body-styles-cls">
  <div></div>
 </body>
</html>

Eg for wffweb:

Html rootTag = new Html(null).give(html -> {
    new Head(html);        
    new Body(html).give(body -> {
        new NoTag(body, "Hello World");            
    });
});
rootTag.setPrependDocType(true);
System.out.println(rootTag.toHtmlString());

will print

<!DOCTYPE html>
<html>
   <head></head>
   <body>
      Hello World
   </body>
</html>

You can also write to OutputStream in specified charset encoding using toOutputStream​(OutputStream os, String charset) method.

RRadley
  • 333
  • 3
  • 7
0

Good way is extracting the style=""s into the head?

sb.append("<style>" +
"td { padding: 6px; border: 1px solid #ccc; text-align: left; }" + 
"th { background: #333; color: white; font-weight: bold; padding: 6px; border: 1px solid #ccc; text-align: left;}" +
"</style>");

helper methods:

void appendTag(StringBuilder sb, String tag, String contents) {
    sb.append('<').append(tag).append('>');
    sb.append(contents);
    sb.append("</").append(tag).append('>');
}
void appendDataCell(StringBuilder sb, String contents) {
    appendTag(sb, "td", contents);
}
void appendHeaderCell(StringBuilder sb, String contents) {
    appendTag(sb, "th", contents);
}
Tiago Medici
  • 1,944
  • 22
  • 22