Over a million developers have joined DZone.

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

·

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 !

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}