updated for 2.4.0

Hello World tutorial FreeMarker#

This tutorial shows how to send the standard "Hello World" from the web-server to the web-browser with ztemplates and FreeMarker.

Prepare#

To enable FreeMarker support, put the freemarker.jar into WEB-INF/lib and add the initialization listener to web.xml, after the ZTemplatesContextListener.


<!-- add this for FreeMarker support -->
<listener>
  <listener-class>
    org.ztemplates.web.freemarker.ZFreeMarkerContextListener
  </listener-class>
</listener>

The View#

  • create a file called HelloWorldFreeMarker.ftl in tutorial/WEB-INF/classes/org/ztemplates/tutorial/helloworld/freemarker with the following content.
<html>
<h1>${message}</h1>
<ul>
<#list items as item>
 <li>${item}
</#list>
</ul>
</html>

The View Model#

  • create a file called HelloWorldFreeMarker.java in tutorial/WEB-INF/classes/org/ztemplates/tutorial/helloworld/freemarker with the following content

package org.ztemplates.tutorial.helloworld.freemarker;

import java.util.ArrayList;
import java.util.List;

import org.ztemplates.render.ZExpose;
import org.ztemplates.render.ZRenderer;
import org.ztemplates.render.freemarker.ZFreeMarkerRenderer;

//this tells ztemplates to use FreeMarker as a renderer
//by default the FreeMarker template has the same name as
//the class but with extension '.ftl'
@ZRenderer(ZFreeMarkerRenderer.class)
public class HelloWorldFreeMarker
{
  @ZExpose
  final String message;

  @ZExpose
  final List<String> items = new ArrayList<String>();

  public HelloWorldFreeMarker()
  {
      message = "Hello World!";
      for(int i=0; i<5; i++)
      {
          items.add("item " + i);
      }
  }
}

The Controller#

  • create a file HelloWorldFreeMarkerAction.java in tutorial/WEB-INF/classes/org/ztemplates/tutorial/helloworld/freemarker with the following content. Note the @ZMatch annotation.

package org.ztemplates.tutorial.helloworld.freemarker;

import org.ztemplates.actions.ZMatch;
import org.ztemplates.web.ZTemplates;

@ZMatch("/helloworld/freemarker")
public class HelloWorldFreeMarkerAction
{
  public void after() throws Exception
  {
    ZTemplates.getServletService().render(new HelloWorldFreeMarker());
  }
}

In the controller we could also have defined the following callbacks:

  • public void before() throws Exception

Build#

  • open a command window and change to the tutorial/WEB-INF/classes directory
  • compile

javac -cp ../lib/ztemplates.jar org/ztemplates/tutorial/helloworld/freemarker/*.java

Run#

Neuen Anhang hinzuf�gen

Du bist nicht autorisiert, Anh�nge zu dieser Seite hochzuladen.
« Diese Seite (Version-) wurde zuletzt am 22-Dez-2013 13:18 von gerdziegler.de ge�ndert.