HtmlDocSerializer
HtmlDocSerializer is an extension of HtmlSerializer that wraps serialized POJOs in a complete HTML document.
This class is used extensively in the creation of POJO-based user interfaces in the REST API.
When to use it
Use HtmlDocSerializer when the output is a page a person opens in a browser: it adds the head, style, navigation links, aside and footer around the serialized data.
For an HTML fragment you embed in another page, use HtmlSerializer.
In a REST resource you rarely build one yourself; the @HtmlDocConfig annotation sets the same options declaratively.
Example
import org.apache.juneau.marshall.html.*;
public class HtmlDocSerializerExample {
public static class Person {
public String name = "John Smith";
public int age = 45;
}
public static void main(String[] args) throws Exception {
// A serializer with a navigation bar and a side note around the data.
HtmlDocSerializer serializer = HtmlDocSerializer.create()
.navlinks("up: request:/..")
.aside("<p>One person.</p>")
.build();
String html = serializer.write(new Person()).toString();
System.out.println(html.contains("<p>One person.</p>") + " " + html.contains("John Smith"));
}
}
The same options in a REST resource:
/**
* Sample REST resource that prints out a simple "Hello world!" message.
*/
@Rest(path="/helloWorld")
@HtmlDocConfig(
navlinks={
"up: request:/..",
"options: servlet:/?method=OPTIONS"
},
aside={
"",
" <p>This page shows a resource that simply response with a 'Hello world!' message</p>",
" <p>The POJO serialized is a simple String.</p>",
""
}
)
class HelloWorldResource extends BasicRestServlet {
// ...
}
Options
The one pre-configured instance is HtmlDocSerializer.DEFAULT.
The builder settings readers reach for first:
| Builder method | Effect |
|---|---|
navlinks(String...) | Links shown in the navigation bar, as label: url strings. |
aside(String...) | HTML for the side section. |
asideFloat(...) | Float the side section to the left or right. |
header(String...) / footer(String...) | HTML for the page header and footer. |
head(String...) | Extra content for the document <head>. |
style(String...) / stylesheet(String...) | Inline CSS, or stylesheet URLs to link. |
script(String...) | Inline JavaScript added to the page. |
nowrap() | Prevent text in table cells from wrapping. |
noResultsMessage(String) | Message shown when there is no data to display. |
template(Class) | The class that writes the page; see below. |
widgets(Class...) | Widgets that contribute scripts, styles and $W{...} variables. |
The HtmlDocSerializer.Builder.template(Class) setting defines a template for the HTML page being generated. The default template is described next.
The class hierarchy for the builder of this serializer is below. Refer to the builder javadocs for the full set of configurable settings.