Tutorial: Play Framework 2.0 Beta with Ebean, JSON & jQuery
This tutorial is a port of James Ward’s Tutorial on building a Web Application with Play 1.2.3 to Play 2.0 Beta. The Play 2.0 Beta is a major re-write of the Play Framework and uses a whole new approach to writing Web Applications. Deployment of the web application to Heroku will be discussed in the next blog post. This tutorial use the Play 2.0 Beta Release on November 16. Documentation is sparse at this point, so I had to make some guesses on how to get some things to work. To make it easier I stuck with the original release instead of updating to the latest source branch.
The source of this tutorial is on github.
Step 1) Download and install Play 2.0 Beta - I unzipped it into a directory called play2beta.
Step 2) Create a new Play app from the command line, using a Java Template:
play new playbars2
For the template choose “Create a simple Java application”
Step 3) Change to the new application’s directory and start the server. It is important to first run the server before trying to load the application in an IDE. This is because it generates a number of dependencies need to compile the application.
cd playbars2 play run
The server is now running at the URL: http://localhost:9000 The beta release does not have URL’s for documentation and JavaDocs.
Optional Step 4) Setup the application in your favorite IDE. Add the following jar files and directories from the framework to this list of dependencies:
play2beta/repository/local/play/play_2.9.1/2.0-beta/jars/play_2.9.1.jar
play2beta/framework/sbt/boot/scala-2.9.1/lib
And then add these directories from the application itself. These are the directories that are generated by the Play Framework.
playbars2/target/scala-2.9.1/classes
playbars2/target/scala-2.9.1/classes_managed
Step 5) Create a basic Model class. Instead of inheriting from the Play Framework Model class, the class extends from the Ebeans Model class. This class provides the basic save, update and delete methods. To get the basic read operations, such as find all, we need to create a Finder. For the most part Ebeans is similar to JPA and uses the same annotations as JPA.
@Entity
public class Bar extends Model {
public String name;
// -- Queries
public static Model.Finder find = new Model.Finder(String.class, Bar.class);
Step 6) Define the routes to the different methods in the conf/routes file:
GET / controllers.Application.index() GET /bars.json controllers.Application.listBars POST / controllers.Application.addBar
The format of the file is still the same. It specifies what URL’s map to what methods. For example we define the URL get request for /bars.json maps to the action of listBars, which returns all the bars in JSON format.
Step 7) To create the web UI we will use reuse the HTML and JQuery from the previous sample. The difference is the Play Framework now uses Scala for the template language. The first page to look at is app/views/main.scala.html The first line declares two variables that will be used in the page:
@(title: String)(content: Html)
These variables are used later in the page to set the actual values of the title and content of the page:
<title>@title</title>
....
<body>
<h1>@title</h1>
@content
</body>
The rest of the page is fairly standard HTML, the only difference is how references to assets and scripts are made. They use a special syntax so that Play can properly resolve the references:
href="@routes.Assets.at("stylesheets/main.css")"
The index.scala.html page also declares two variables, which are referenced later:
@(message: String)(barForm: Form[Bar])
The syntax for declaring the form variable, barForm, is similar to Java Generics and declares the type of the form. Form[Bar] means the type of the Form will be the Bar model. It then includes the main.scala.html page and defines values for the first two variables of main, title and content:
@main("Welcome to PlayBar 2") { ...... }
The content between { } is the content that is put into the main page. The content of the page declares the HTML form that is used to add a bar and tells what action to use to process the form, the addBar method in Application. It also defines an ID, barForm, which is used to reference the form:
@form(action = routes.Application.addBar, args = 'id -> "barForm") {
@inputText(
field = barForm("name"),
args = 'label -> "Name of bar?", 'placeholder -> "Foo Bar"
)
<p class="buttons">
<input type="submit">
<p>
}
When the submit button is clicked, the results will be routed to addBar.
Step 8) Add JSON support. JSON support is now included in the latest source code of the Play Framework, but is not in the early beta. As a work around I included the source to encode Objects to json in my sample (copied from the Play Source code). The Jackson JSON libraries also need to be added to the list of project dependencies. By adding them to Build.scala, when we deploy to Heroku it will be able to also download the necessary jar files. Modify the file to add the following lines:
val jacksonCoreAsl = "org.codehaus.jackson" % "jackson-core-asl" % "1.9.2" val jacksonMapperAsl = "org.codehaus.jackson" % "jackson-mapper-asl" % "1.9.2" val appDependencies = Seq( // Add your project dependencies here, jacksonCoreAsl, jacksonMapperAsl )
Step 9) Next we need to define the methods that do all the server processing in “app/controllers/Application.java”. As opposed to the previous version of play, all of the methods return a Result class. The Result ok method is used to return a 200 OK Result, along with the data to be returned. When the application is first load it will call the Application method index. That method references the index.html.scala page and defines the two values to be used for message and barForm, defined at the first of the index page:
return ok(index.render("Enter the name of your new bar:", form(Bar.class)));
Another big difference with Play 2.0 is how forms are processed. Instead of passing the model class into the method, you create a new instance of a form based of your class. In the addBar we create a form object and have it bind the data from the request for processing. Once we have the bar we can use the inherited methods from Ebeans model to save the model.
Form form = form(Bar.class).bindFromRequest();
if (form.hasErrors()) {
return badRequest(index.render("Error in Bar form. Enter new Bar",form(Bar.class)));
} else {
Bar bar = form.get();
bar.save();
return ok( index.render("The bar " + bar.name + " was saved. Enter a new Bar:", form(Bar.class)));
}
Then to list the bars we use the findAll we defined in the Bar model class and convert the results to JSON:
return ok(toJson(Bar.findAll()));
Now you can test the application by going to: http://localhost:9000/
We now have a working Play 2.0 Beta web application. Deployment of the web application to Heroku requires a number of extra steps and will be discuss in the next blog post. This sample is also lacking several things, which will be covered in other tutorials (things such as tests and flexible configuration).
Java,
Play Framework
Reader Comments