Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building HTML in Java code only

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

like image 1000
marioosh Avatar asked Jul 28 '11 08:07

marioosh


2 Answers

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.

like image 150
AlexR Avatar answered Oct 22 '22 11:10

AlexR


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();
like image 41
Alvin Avatar answered Oct 22 '22 13:10

Alvin