Play Framework Tutorial for Rails Developers

Posted on by Jeremiah Hemphill

I am primarily a Ruby on Rails developer who was tasked with learning and working the Play framework. After using the Play framework for several months, I have found the documentation lacking. Like Ruby on Rails, it is simple to go from nothing to a working, running MVC app. Unlike Rails, there are very few examples and tutorials to move forward form the basic application.

For a beginning user, great tutorials exist including the creating a new application tutorial and Play 2.0 for Java developers.

We decided to write a sample Play application and walkthrough for the more esoteric parts of the Play framework. The sample project and tutorial is located on github.

Play Java Framework

The sample project models a library that checks books in and out to patrons. It includes an admin section that lets you manage the entire system and a frontend that checks books in and out. In addition to the standard MVC code, we have added our own validation system to streamline code in the controllers. Our goal main goal for this project is to demonstrate more complex database interactions and form interactions than in the default Play samples.

In the tutorial, we cover topics that we had trouble with. Each topic addresses a simple problem that took us too long to solve. One example is how to directly access data in a post request without binding it to a form object. In the play framework, this code is required to read the “name” input from a form and avoid throwing an exception.

String name = "";
if(request().body().asFormUrlEncoded().containsKey("name"))  {
   name = request().body().asFormUrlEncoded().get("name").toString();
}  

The tutorial includes a more in depth explanation and solution for this and the other problems we encountered working on Play. The topics include:

  • Model attribute decorators
  • Model validations
  • Parsing JSON in Java
  • Multiple database setup
  • Seeding the database
  • Saving vs updating models in controllers
  • Reading posted form inputs
  • How to handle a form with errors on the view
  • Controller based validations and our validation framework
  • Routes on controllers outside of the default package
  • Setting HTTP headers

Download the code, read the readme, and run the project. Hopefully it answers a few questions you have about Play. We would have killed to have this information when we started. The code and tutorial are located on github. If anything is confusing or if you have found problem that we haven’t covered, leave a comment below. We would be happy to help.

 
comments powered by Disqus