Tuesday, September 13, 2011

The Play Framework - Part 4

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.


A special template syntax is used to link to other pages in the application (the actual URL of the page is not used). This makes things more flexible, because you can change the page's URL in the "conf/routes" file without having to go through each template file and edit all the links that point to that page. Take this example:

Template file:

<a href="@{Application.index()}">Home</a>

"conf/routes" file:

GET  /home   Application.index

Generated HTML:

<a href="/home">Home</a>

Play sees that the Application.index method is assigned to the URL "/home" and generates the appropriate HTML when a user requests the page.

To access a static resource (like images, Javascript files, and CSS files), put the path to that resource in single quotes. With Play, all static resources go in the "public" directory.

<script src="@{'/public/javascripts/jquery-1.4.2.min.js'}"></script>

As with seemingly every type of file in a Play application, any changes made to the "conf/routes" file while the application is running are applied immediately. No restart is needed.

The "form" template tag can be used to create HTML forms:

#{form @Application.postComment(post.id)}
  Name: <input type="text" name="author" value="${params.author}" />
  <input type="submit" value="Post" />
#{/form}

This ends up adding two more attributes to the generated <form> tag ("accept-charset" and "enctype") and also adds a hidden parameter called "authenticityToken" (probably used for security purposes). You can also add attributes of your own, by supplying them as tag parameters after the action URL:

#{form @Application.postComment(post.id), onsubmit:'return validateForm()'}

No comments: