WebMacro

BACK | UP | NEXT

What is it?

WebMacro is a page generator which introspects ordinary Java objects to extract their properties and drop them into a template. Typically you use it to create an HTML view of a set of Java objects.

You can use WebMacro under a Java servlet to generate HTML, XML, or other formats in response to web requests. You can also use WebMacro offline to generate the same pages from a batch processing job: WebMacro is not tied to the servlet API.

How does a programmer use it?

Here is the simplest way:
   WebMacro wm = new WebMacro(); // probably just once in your servlet
   FastWriter out = new FastWriter(outStream); // create a FastWriter

   Context c = wm.getContext();  // do this every request
   c.put("query", queryString);  // put ordinary Java object: a string?
   Result[] res = ...;           // some data: maybe search results?
   c.put("results", res);        // put complex objects in here too!

   Template t = wm.getTemplate("search.view");
   t.write(out, context);
The key steps here are:
  • Put your application data into a Context
  • Load a Template
  • write: WebMacro applies your Context to the Template
The most important point is that the objects you put into the context are plain, vanilla, ordinary Java objects: WebMacro performs class analysis to figure out how to extract the data required by the Template.

This means that as a programmer you concentrate on writing ordinary Java objects, without regard to how they are rendered in the final page view. Your code looks and feels like what it is: pure Java code.

How does a template writer use it?

Given the servlet code above, an over-simplified "search.view" might look like this:
  <html><head><title>Search Results</title></head>
  <body>
  <h1>Here are the results for $query:</h1>
  <table>
  #foreach $result in $results {
    <tr><td>$result.Number</td>
    <td><a href="$result.Link">$result.Name</a></td></tr>
  }
  </table>
  </body></html>
The main point is that this is pretty much ordinary HTML. There is an extremely simple scripting code here, but the logic relates to how the page is going to look. Nothing in the template describes how the search result was obtained, nor is there any business logic here. The logic on the page is page logic.

WebMacro would replace $queryString with the string you added to the context. Next it would loop through the Result array looking at each element and working out how to extract the properties "Name", "Number", and "Link" from whatever sort of objects happened to be in the array.

WebMacro follows the JavaBeans standard when performing this analysis, and might find a result.Number field, a result.getLink() method, and perhaps might resort to result.get("Name") to extract the Name field. The particulars would depend on the actual Java definition of the Result class.


BACK | UP | NEXT