Programmatic HTMLDocument generation using Java

前端 未结 9 1888
孤独总比滥情好
孤独总比滥情好 2021-02-14 03:34

Does anyone know how to generate an HTMLDocument object programmatically in Java without resorting to generating a String externally and then using HTMLEditorKit#read to parse i

9条回答
  •  走了就别回头了
    2021-02-14 04:21

    I'd look into how JSPs work - i.e., they compile down into a servlet that is basically one huge long set of StringBuffer appends. The tags also compile down into Java code snippets. This is messy, but very very fast, and you never see this code unless you delve into Tomcat's work directory. Maybe what you want is to actually code your HTML generation from a HTML centric view like a JSP, with added tags for loops, etc, and use a similar code generation engine and compiler internally within your project.

    Alternatively, just deal with the StringBuilder yourself in a utility class that has methods for "openTag", "closeTag", "openTagWithAttributes", "startTable", and so on... it could use a Builder pattern, and your code would look like:

    public static void main(String[] args) {
        TableBuilder t = new TableBuilder();
        t.start().border(3).cellpadding(4).cellspacing(0).width("70%")
          .startHead().style("font-weight: bold;")
            .newRow().style("border: 2px 0px solid grey;")
              .newHeaderCell().content("Header 1")
              .newHeaderCell().colspan(2).content("Header 2")
          .end()
          .startBody()
            .newRow()
              .newCell().content("One/One")
              .newCell().rowspan(2).content("One/Two")
              .newCell().content("One/Three")
            .newRow()
              .newCell().content("Two/One")
              .newCell().content("Two/Three")
          .end()
        .end();
        System.out.println(t.toHTML());
    }
    

提交回复
热议问题