简体   繁体   English

用Java构建HTML文件的最佳方法是什么?

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

I'm generating an HTML formatted log in Java. 我正在Java中生成HTML格式的日志。 Is there a data structure that is best suited for storing HTML? 是否有最适合存储HTML的数据结构?

This doesn't seem very clean to me: 这对我来说似乎不是很干净:

String html_header = "<!DOCTYPE html>\n<html><head><title>blah</title>...</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? 创建一个可以通过Java读取的HTML模板的数据文件会更好吗?

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: 如果要使用对象构建文档结构,则可以使用DOM4j,它将允许您编写如下代码:

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. 雅加达的元素构造集提供了一个类似的API,该API也更特定于HTML。

Alternatively, you can include a template engine that would allow you to write HTML files with placeholders for variable values and basic logic. 另外,您可以包括一个模板引擎,该引擎将允许您使用带有占位符的HTML文件来编写变量值和基本逻辑。 Then you would combine these templates with your data to generate the final HTML. 然后,您可以将这些模板与数据结合起来以生成最终的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. FreeMarker是一种使用非常广泛的引擎,如果您不介意花一些时间学习其模板语言,它将为您提供很大的灵活性。

If you go this route, you would create a template like the following: 如果走这条路线,您将创建一个类似于以下内容的模板:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM