Nabedge has posted 2 posts at DZone. You can read more from them at their website. View Full User Profile

Template engine Mixer2 - Let's write view of MVC by java and XHTML

10.03.2013
| 871 views |
  • submit to reddit

Mixer2 is a XHTML dedicated template engine. You can use it as an alternative technology for JSP or Velocity. Also, you can use Mixer2 for non-web application such as sending HTML e-mail inside the batch application.

Here is the hello world sample.

HelloWorld.java
import java.io.File;
import org.mixer2.Mixer2Engine;
import org.mixer2.jaxb.xhtml.Div;
import org.mixer2.jaxb.xhtml.Html;

public class HelloWorld {

    public static void main(String[] args) throws Exception {
        Mixer2Engine m2e = new Mixer2Engine();
        Html html = m2e.loadHtmlTemplate(new File("HelloWorld.html"));
        html.getById("hellomsg",Div.class).unsetContent();
        html.getById("hellomsg",Div.class).getContent().add("Hello World !");
        System.out.println(m2e.saveToString(html));
    }

}
HelloWorld.html template
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="hellomsg">here comes message.</div>
</body>
</html>
Result
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="hellomsg">Hello World !</div>
</body>
</html>

As you see, the template is 100% pure xhtml/css . No custom tag or any other syntax that breaks the html template as a efforts of web designer.

The web developer can write code with usual java knowledge because Mixer2 parses the template and map html tags into each java type object.

This means that you can write easily JUnit test case for view of M,V,C . The test case is below.

code
public class Sample {

    public Html createHtml(String message) throws IOException, TagTypeUnmatchException {
        Mixer2Engine m2e = new Mixer2Engine();
        Html html = m2e.loadHtmlTemplate(new File("Sample.html"));
        html.getById("foo", Div.class).unsetContent();
        html.getById("foo", Div.class).getContent().add(message);
        return html;
    }

}
test case for the above code
public class SampleTest {

    @Test
    public void executeHtmlTest() throws IOException, TagTypeUnmatchException {
        Sample sample = new Sample();
        Html html = sample.createHtml("aaa");
        assertEquals("aaa",html.getById("foo", Div.class).getContent().get(0));
    }

}

There is a "fruit shop" sample web application based on Spring MVC 3 and Mixer2. See the official site for detail. Thank you !

0
Published at DZone with permission of its author, Nabedge Watanabe.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)