Abdul Habra's Blog
Build CRUD Apps With Play Framework

Introduction

Play (playframework.org) is a Java framework that makes it very easy to build web applications. Here I show how to build a CRUD web app in a way that reminds me of RoR or Grails. You only need to know Java to follow this example. Play’s website contains excellent documentation and I will not repeat them here.

Some of the material here was presented at CoJug on 2010.06.08. The CoJug presentation contained more than what is provided here, and was presented by Nilanjan Raychaudhuri and myself.

Setup

  1. Java 1.5 or higher installed.
  2. Play installed, remember to add Play’s location to the path.
  3. Eclipse 3.5 installed. (This is a personal choice, you may use any IDE or text editor).

This will be a simple CRUD application which manages the following entities:

  1. A group of companies.
  2. Each Company can have 0 or more Department.
  3. Each Department can have 0 or more Employee.

Create App’s Skeleton

  1. From the command line, navigate to the directory which will contain the new application.
  2. Run this command: play new corporations
  3. You will be prompted to enter the application’s name, enter Corporations
  4. The above will create an empty Play application in the corporations directory.
  5. To try what you created, run this command:

      cd corporations
     
    play run
  6. In your web browser, go to http://localhost:9000/
  7. You should get a page titled “Your application is ready !”
  8. This proves that Play is running and that you application has started.

Configure The App

  1. Terminate the Play running app at the command line: Ctrl-C
  2. We are going to use Eclipse for developing this app, so from the command line, enter: play eclipsify
  3. The eclipsify command creates Eclipse artifacts like .settings and .project
  4. Run Eclipse
  5. Import this project: File/Import/General/Existing projects into Workspace
  6. Navigate to the corporations directory which you created earlier.
  7. Finish importing the project.
  8. In my Eclipse’s instance, I got several errors after the import, the errors where complaining about different version of Java being used. I changed the project’s properties/Java compiler to JDK 1.5, and that resolved the problem.
  9. Open the file conf/application.conf and enable the line

    db=mem

    which will run HSQL in memory (this is only a demo, but if you look in the file you could see how to connect to a real database)
  10. Still in conf/application.conf, find the section titled “Additional modules” and either enable or add the following line:

    module.crud=${play.path}/modules/crud

    Which will tell Play to include default CRUD scaffolding.
  11. Open the file conf/routes and add this line

    *      /admin              module:crud

    which will route all CRUD operations to /admin
  12. Go to the command line (in the corporations directory) and run “play eclipsify” again.
  13. Refresh the eclipse project (F5), (you may have to reset the Java Compiler to 1.5 again).
  14. From the command line, do “play run” again, then check in the browser. The app should run as we had it before, no changes yet.

Create Employee Model and Controller

Keep Play running at the command line.

In Eclipse, navigate to app/models the create a new class Employee:

package models;
import java.util.Date;
import javax.persistence.*;
import play.db.jpa.Model;

@Entity
public class Employee extends Model {
  public String fullName;
  public Integer salary;
  public Date dateOfHire;
}

Navigate to app/controllers and create a new class Employees:

package controllers;
public class Employees extends CRUD { // an empty class
}

Make sure to save the files, and that Play is still running at the command line. In your web browser, go to http://localhost:9000/admin

You should see this page:

Try To Add an employee and see what happens.

Notice how Play’s convention for the controller’s name is just to add “s” at the end of the model class name. (model=Employee, controller=Employees). This is the default convention which can be changed as will be shown when we do the Company controller.

Notice also that our choice for the Employee class to be in the models package directly is only for simplicity. It can be in any sub-package under models. The same is true for the Employees class and controllers package.

Create Department Model and Controller

In Eclipse, navigate to app/models the create a new class Department:

package models;
import javax.persistence.*;
import play.db.jpa.Model;

@Entity
public class Department extends Model {
public String name;
public String description;
}

Navigate to app/controllers and create a new class Departments:

package controllers;

public class Departments extends CRUD {}

Make sure to save the files, and that Play is still running at the command line. In your web browser, go to http://localhost:9000/admin

You should see the same Administration page as above but now it contains both Departments and Employees object types.

Relationship Between Employee and Department

So far when you add an employee, you cannot specify what department the employee belongs to. Let’s fix that. In the Employee class add the following:

  @ManyToOne
public Department department;

The @ManyToOne is a JPA annotation (in javax.persistence) which says that many Employees can belong to one Department.

Save your work in Eclipse, then try to add a new Employee in the browser. You should see a new field titled “department” with a combo box list of options. If the department list is empty, then add a department, then try to add an employee again, you will see the added department in the list.

Create Company Model and Controller

Create the Company class in the models package:

package models;
import javax.persistence.Entity;
import play.db.jpa.Model;

@Entity
public class Company extends Model {
public String name;
public String address;
public boolean isPublic;
}

Next we want to create the controller for the Company model. The naming convention is to add “s” at the end of the model’s name to create a controller. However, Companys does not spell right in English. The correct English spelling is Companies, so let’s create this class in app/controllers:

package controllers;
import models.Company;

@CRUD.For(Company.class)
public class Companies extends CRUD {}

Notice how we use the @CRUD.For annotation to indicate that this controller class is for the Company model object.

To set the relationship between Department and Company, add the following to the Department model class:

  @ManyToOne
public Company company;

Which says that many departments can belong to one company.

Save your work in Eclipse, then refresh the browser. Notice how companies is added to the list of object types.

Fixing Model Lists

So far when you view the Companies list (for example) you see a list of Company[id] items. This is not too helpful, and the fix is very easy. Edit the model object and provide a toString() method that returns a more readable representation of the model object. For example, in the Company class, add the following:

  public String toString() {
return name;
}

Save and refresh the browser, you should see a more readable list of companies. You can use the same approach for Employee and Department.

Validation

Suppose you want to make the Employee’s fullName required, and that it should not exceed 100 characters in length. Add the following annotations to the fullName declaration:

@Required @MaxSize(100) public String fullName;

Both annotations are imported from play.data.validation.

Now if you try to add a new Employee, notice the comment under the fullName text field.  If you try to save an Employee without providing a fullName, you will get an error message.

The are other interesting validation annotations like:

  • @Email
  • @InFuture for future dates
  • @InPast for past dates
  • @Match for regular expressions matching
  • @Max
  • @Min
  • @Range for a range of values
  • @URL
  • and others …

Change Employee List View

So far, when you view the Employee list, you will see a list of Employee names (assuming you added to toString() method). Suppose you want to change this view to see more details, like salary and dateOfHire. Again, Play provides a simple solution.

  1. At the command line, stop play: Ctrl-C
  2. Run this command

    play crud:ov --template Employees/list

    which will create the new file: app/views/Employees/list.html
  3. Run Play again

    play run
  4. Refresh Eclipse (F5)
  5. In Eclipse, open the new file: app/views/Employees/list.html
    This file shows the default display for a list of Employees.
  6. Look for the div with id=”crudListTable” and change the div’s content to

    #{crud.table fields:['fullName', 'dateOfHire', 'salary'] /}
  7. Save the file.
  8. In the browser, refresh the list of Employees and notice how it contains three columns now.

Change Labels of Fields

Play uses the name of the field in the model object as the label for that field. To change that, open conf/messages file and add the following line:

fullName=Full Name

Save the file. Try to add a new Employee in the browser. Notice how the label for fullName has changed. You can do the same thing for any field name you choose.

Conclusion

This blog touched only one module (CRUD) of Play. Play contains many other modules which make the life of Java web programmer easier. Examples include:

  1. Security.
  2. Spring, and Guice integration.
  3. GWT
  4. Scala and Akka integration.
  5. Maven dependency

The main advantages of Play as I see it are:

  • The quick development feedback cycle: code-save-browserRefresh. Play has removed the need to compile/deploy as used in typical Java web frameworks.
  • Testability: I have not talked about testability here because I wanted to show CRUD support at its simplest, but Play has great testing support, which you can read about at Play’s test documentation.
  1. gene-bryan reblogged this from ahabra and added:
    http://localhost:9000/You...started.Read More
  2. gustavoarjones reblogged this from ahabra
  3. ikeikeredking reblogged this from ahabra
  4. ahabra posted this
Blog comments powered by Disqus