开发者

What is the best way to build an HTML file with Java?

I'm generating an HTML formatted log in Java. Is there a data structure that is best suited for storing HTML?

This doesn't seem very clean to me:

String html_header = "<!DOCTYPE html>\n<html><head><title>blah</title>.开发者_Python百科..</html>";

This can become especially ugly when I need to use attributes in a tag and must escape the quotes around that attribute.

Would it be better to create a data file that is a HTML template which I can read through Java?


Depending on your exact needs, you would have several options. If you want to build a document structure out of objects, you could use DOM4j, which would allow you to write code like this:

Document document = DocumentHelper.createDocument();
Element html = document.addElement( "html" );
Element head = html.addElement("head");
head.addElement("title").addText("blah");

Element body = html.addElement("body")
// etc

This structure could then be converted to a string, and all of the formatting details (opening/closing tags, enclosing attributes, etc.) would be handled for you. Jakarta's Element Construction Set provides a similar API that is more HTML-specific as well.

Alternatively, you can include a template engine that would allow you to write HTML files with placeholders for variable values and basic logic. Then you would combine these templates with your data to generate the final HTML. FreeMarker is a very widely used engine that will give you a lot of flexibility, if you don't mind spending a little time learning their template languages.

If you go this route, you would create a template like the following:

<html>
    <head>
    <title>${myTitle}</title>
    </head>
    <!-- blah -->
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜