Saturday, September 10, 2011

The Play Framework - Part 3

The Play Framework is a MVC web application framework for Java that focuses on being light-weight and easy to use--two qualities that you don't see very often in the Java web application world.


If you want to execute some code when the application first starts up, you can create a class that has the @OnApplicationStart annotation and that extends the Job class. Put the code that you want to run on startup in a method called doJob(). This class can just go in the default package for simplicity, but it doesn't matter what package the class is in.

@OnApplicationStart
public class Bootstrap extends Job {
  @Override
  public void doJob(){
    if (User.count() == 0){
      Fixtures.loadModels("initial-data.yml");
    }
  }
}

In DEV mode, this will be run when the application gets its first request. That way, if an error occurrs, it will appear in the browser. But in PROD mode, the startup code will be run as soon as the play run command is executed and if there are any errors, the server will fail to start up.

To pass variables to a template, simply pass them as arguments to the render() method in the controller. The variable will have the same name inside the template as it does inside the controller.

If you want to run some code every time a controller handles a request, use the @Before annotation. For example, the addDefaults() method below will add two variables to the template every time a request comes in to the Application controller (the Play.configuration variable allows you to access values from the 'application.conf" file):


public class Application extends Controller {
  @Before
  public static void addDefaults(){
    //called before every request is handled
    renderArgs.put(
      "blogTitle",
      Play.configuration.getProperty("blog.title")
    );
    renderArgs.put(
      "blogBaseline",
      Play.configuration.getProperty("blog.baseline")
    );
  }

  //...
}

Play adds some helpful utility methods to various datatypes inside template code. Calling pluralize() on a number will return the string "s" if the number is not 1. Calling format('MM/dd/yyyy') on a Date object will format the date according to the given format string (you don't need to create a SimpleDateFormat object). Calling nl2br() on a string will replace all newlines with <br/> tags.

Tags are snippets of template code that you can insert into other templates by calling them like functions. The tag parameter names all begin with underscores in the tag file. Tag files go in the "views/tags" directory. The tag's name is the same as its file name (minus the file extension).

Calling a tag from a template:

#{hello person:'George', timeOfDay:'morning' /}

Tag file (views/tags/hello.html):

Good ${_timeOfDay}, <b>${_person}</b>!

No comments: