Documentation

You are viewing the documentation for Play 1. The documentation for Play 2 is here.

Starting up the project (Scala version)

Introduction

In this tutorial you will learn the play framework by coding a real web application, from start to finish. In this application, we will try to use everything you would need in a real project, while introducing good practices for play application development.

We have split the tutorial into several independent parts. Each part will introduce more complex features, and provide everything that a real project needs: validation, error handling, security, an automated test suite, a shiny web interface, an administration area, etc.

All the code included in this tutorial can be used for your projects. We encourage you to copy and paste snippets of code or steal whole chunks.

The project

We chose to create yet another blog engine. It’s not a very imaginative choice but it will allow to explore most of the functionality needed by a modern web application.

To complicate things a bit we will manage several users with different roles (editor, admin).

We will call this blog engine project yabe.

This application is distributed as a sample application as well. You can retrieve the final code in the samples-and-tests/yabe-with-scala directory of your play installation.

Prerequisites

First of all, make sure that you have a working Java installation. Play requires Java 5 or later.

As we will use the command line a lot, it’s better to use a Unix-like OS. If you run a Windows system, it will also work fine; you’ll just have to type a few commands in the command prompt.

We will assume that you are familiar with Java and Web development (especially HTML, CSS and Javascript). Additionally, this version of the tutorial assumes a bit of familiarity with Scala, although we won’t use many exotic features and will explain as we go. You don’t need to have a deep knowledge of all the JEE components. Play is a ‘full stack’ Java framework and it provides or encapsulates all the Java APIs you will need. No need to know how to configure a JPA entity manager or deploy a JEE component.

You will of course need a text editor. If you are accustomed to use a full featured Java IDE like Eclipse or Netbeans you can of course use it. However with play you can have fun working with a simple text editor like TextMate, Emacs or VI. This is because the framework manages the compilation and the deployment process itself. We will soon see that...

Note that support for Scala in the major IDEs is far less mature than for Java, so we really suggest using a text editor to start with.

Later in this tutorial we will use Lighttpd and MySql to show how to deploy a play application in a ‘production’ mode. But Play can work without these components so if you can’t install them, it’s not a problem.

Installation of the play framework

Installation is very simple. Just download the latest binary package from the download page and unzip it to any path.

If you’re using windows, it is generally a good idea to avoid space characters in the path, so for example c:\play would be a better choice than c:\Documents And Settings\user\play.

To work efficiently, you need to add the play directory to your working path. It allows to type just 'play' at the command prompt to use the play utility. To check that the installation worked, just open a new command line and type 'play'; it should show you the play basic usage help.

Project creation

Now that play is correctly installed, it’s time to create the blog application. Creating a play application is pretty easy and fully managed by the play command line utility. That allows for standard project layouts between all play applications.

Open a new command line and type:

~$ play new yabe-with-scala --with scala

It will prompt you for the application full name. Type 'Yet Another Blog Engine'.

The 'play new' command creates a new directory yabe-with-scala/ and populates it with a series of files and directories, the most important being:

app/ contains the core of the application, split between models, controllers and views directories. It can contain other Java packages as well. This is the directory where *.java and *.scala source files live.

conf/ contains all the configuration files of the application, especially the main application.conf file, the routes definition files and the messages files used for internationalization.

lib/ contains all optional Java/Scala libraries packaged as standard .jar files.

public/ contains all the publicly available resources, which includes Javascript files, stylesheets and images directories.

test/ contains all the application tests. Tests are either written either as Java JUnit tests or as Selenium tests.

Because play uses UTF-8 as single encoding, it’s very important that all text files hosted in these directories are encoded using this charset. Make sure to configure your text editor accordingly.

Now if you’re a seasoned Java developer, you may wonder where all the .class files go. The answer is nowhere: play doesn’t use any class files but reads directly the java source files. Under the hood we use the Eclipse compiler to compile Java sources on the fly, as well as the standard Scala compiler for scala files.

That allows two very important things in the development process. The first one is that play will detect changes you make to any Java/Scala source file and automatically reload them at runtime. The second is that when a Java exception occurs, play will create better error reports showing you the exact source code.

In fact play can keep a bytecode cache in the application /tmp directory, but only to speed up things between restart on large applications. You can discard this cache using the 'play clean' command if needed.

Running the application

We can now test the newly created application. Just return to the command line, go to the newly created yabe-with-scala/ directory and type 'play run'. Play will now load the application and start a Web server on port 9000.

You can see the new application by opening a browser to http://localhost:9000. A new application has a standard welcome page that just tells you that it was successfully created.

Let’s see how the new application can display this page.

The main entry point of your application is the conf/routes file. This file defines all accessible URL of the application. If you open the generated routes file you will see this first ‘route’:

GET		/			Application.index

That simply tells play that when the web server receives a GET request for the / path, it must call the Application.index Scala method. In this case, Application.index is a shortcut for controllers.Application.index, because the controllers package is implicit.

A play application has several entry points, one for each URL. We call these methods 'action' methods. Action methods are defined in special objects which we call 'controllers'.

Let’s see what the controllers.Application controller looks like. Open the yabe-with-scala/app/controllers/Application.scala source file:

package controllers
 
import play._
import play.mvc._
 
object Application extends Actions {
    
    def index = render()
    
}

As you see, a controller is not a class but an object. It extends the play.mvc.Actions class. This class provides all useful methods for controllers, like the render() method we use in the index action.

Scala objects are always single instances (singletons) and are automatically initialized the first time one of their methods is called. All their methods correspond with static methods in Java.

The type signature of the index action is not visible here, it’s inferred from the body of the method. If we wanted to be explicit, we would write def index(): Unit = {…} which means: a method with no parameters and no return value (Unit is Scala’s name for Java’s void).

The default index action is simple: it calls the render() method which tells play to render a template. Using a template is the most common way (but not the only one) to generate the HTTP response.

Templates are simple text files that live in the /app/views directory. Because we didn’t specify a template, the default one for this action will be used: Application/index.html

To see what the template looks like, open the /yabe/app/views/Application/index.html file:

#{extends 'main.html' /}
#{set title:'Home' /}
 
#{welcome /}

The template content seems pretty light. In fact, all you see are play tags. Play tags are very close to JSP tags as defined in a taglib. It is the #{welcome /} tag that generates the welcome message you’ve seen in the browser.

The #{extends /} tags tells play that this template inherits another template called main.html. Template inheritance is a powerful concept that allows you to create complex web pages by reusing common parts.

Open the /yabe/app/views/main.html template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>#{get 'title' /}</title>		
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <link rel="stylesheet" type="text/css" media="screen" 
            href="@{'/public/stylesheets/main.css'}" />
        <link rel="shortcut icon" type="image/png" 
            href="@{'/public/images/favicon.png'}" />
    </head>
    <body>
        #{doLayout /} 
    </body>
</html>

Do you see the #{doLayout /} tag? This is where the content of Application/index.html will be inserted.

We can try to edit the controller file to see how play automatically reloads it. Open the yabe/app/controllers/Application.scala file in a text editor, and add a mistake by calling a non-existent method:

def index = reindeer()

Go to the browser and refresh the page. You can see that play detected the change and tried to reload the Application controller. But because you made a mistake, you get a compilation error.

Ok, let’s correct the error, and make a real modification:

def index {
    println("Yop")
    render()
}

Notice that we’ve added curly braces now that the index action involves multiple statements and, because this method has no return value, we’ve removed the equals sign.

This time, play has correctly reloaded the controller and replaced the old code in the JVM. Each request to the '/' URL will output the ‘Yop’ message to the console.

You can remove this useless line, and now edit the yabe/app/views/Application/index.html template to replace the welcome message:

#{extends 'main.html' /}
#{set title:'Home' /}
 
<h1>A blog will be there</h1>

Like for Scala code changes, just refresh the page in the browser to see the modification.

We will now start to code the blog application. You can either continue to work with a text editor or open the project in a Scala IDE like Eclipse or Netbeans. If you want to set up a Scala IDE, please check this page.

Setting up the database

One more thing before starting to code. For the blog engine, we will need a database. For development purposes, play comes with a standalone SQL database management system called HSQLDB. This is the best way to start a project before switching to a more robust database if needed. You can choose to have an in-memory database or a filesystem database that will keep your data between application restarts.

At the beginning, we will do a lot of testing and changes in the application model. For that reason, it’s better to use an in-memory database so we always start with a fresh data set.

To set up the database, open the yabe/conf/application.conf file and uncomment this line:

db=mem

As you see in the comments, you can easily set up any JDBC compliant database and even configure the connection pool.

Now, go back to your browser and refresh the welcome page. Play will automatically start the database. Check for this line in the application logs:

INFO  ~ Connected to jdbc:hsqldb:mem:playembed

Using a version control system (VCS) to track changes

When you work on a project, it’s highly recommended to store your source code in a VCS. It allows you to revert to a previous version if a change breaks something, work with multiple people and give access to all the successive versions of the application. Of course you can use any VCS to store your project, but here we will use Bazaar as an example. Bazaar is a distributed source version control system.

Installing bazaar is out of the scope of this tutorial but it is very easy for any system. Once you have a working installation of bazaar, go to the yabe-with-scala directory and initialize the application versioning by typing :

$ bzr init

When storing a play application in a VCS, it’s important to exclude the tmp/ and logs/ directories.

$ bzr ignore tmp
$ bzr ignore logs

Now we can commit our first blog engine version :

$ bzr add
$ bzr commit -m "YABE inital version"

Version 1 is committed and we now have a solid foundation for our project.

Go to the next part.