# Your first Play application Let’s write a simple to do list application with Play 2.0 and deploy it to the cloud. ## Prerequisites First of all, make sure that you have a [[working Play installation|Installing]]. You only need Java (version 6 minimum), and to unzip the Play binary package to start; everything is included. 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. You will of course need a text editor. You can also use a Scala IDE such as Eclipse or IntelliJ if you like. 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. ## Project creation Now that Play is correctly installed, it’s time to create the new 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. On the command line type: ``` $ play new todolist ``` It will prompt you for a few questions. Select the _Create a simple Scala application_ project template. [[images/new.png]] The `play new` command creates a new directory `todolist/` and populates it with a series of files and directories, the most important being: - `app/` contains the application’s core, split between models, controllers and views directories. This is the directory where .scala source files live. - `conf/` contains all the application’s configuration files, especially the main `application.conf` file, the `routes` definition files and the `messages` files used for internationalization. - `project` contains the build scripts. The build system is based on sbt. But a new Play application comes with a default build script that will just work fine for our application. - `public/` contains all the publicly available resources, which includes JavaScript, stylesheets and images directories. - `test/` contains all the application tests. Tests are written as Specs2 specifications. > 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. ## Using the Play console Once you have an application created, you can run the Play console. Go to the new `todolist/` directory and run: ``` $ play ``` This launches the Play console. There are several things you can do from the Play console, but let’s start by running the application. From the console prompt, type `run`: ``` [todolist] $ run ``` [[images/run.png]] The application is now running in development mode. Open a browser at [[http://localhost:9000/]]: [[images/welcome.png]] > **Note:** Read more about [[The Play Console|PlayConsole]]. ## Overview 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 of the application’s accessible URLs. If you open the generated routes file you will see this first _route_: ``` GET / controllers.Application.index ``` That simply tells Play that when the web server receives a GET request for the / path, it must retrieve the `Action` to execute from the `controllers.Application.index` method. Let’s see how the `controllers.Application.index` method looks like. Open the `todolist/app/controllers/Application.scala` source file: ``` package controllers import play.api._ import play.api.mvc._ object Application extends Controller { def index = Action { Ok(views.html.index("Your new application is ready.")) } } ``` You see that `controllers.Application.index` returns an `Action` that will handle the request. An `Action` must return a `Result` that represents the HTTP response to send back to the web browser. > **Note:** Read more about [[Actions|ScalaActions]]. Here the action returns a **200 OK** response filled with HTML content. The HTML content is provided by a template. Play templates are compiled to standard Scala functions, here as `views.html.index(message: String)`. This template is defined in the `app/views/index.scala.html` source file: ``` @(message: String) @main("Welcome to Play 2.0") { @play20.welcome(message) } ``` The first line defines the function signature. Here it takes a single `String` parameter. Then the template content mix HTML (or any text based language) with Scala statements. The Scala statements starts with the special `@` character. ## Development workflow Now let’s make some modifications to the new application. In the `Application.scala` change the content of the response: ``` def index = Action { Ok("Hello world") } ``` With this change the **index** action will now respond with a simple `text/plain` **Hello world** response. To test this change, just refresh the home page in your browser: [[images/hello.png]] There is no need to compile the code yourself or restart the server to see the modification. It is automatically reloaded when a change is detected. But what happens when you make a mistake in your code? Let’s try: ``` def index = Action { Ok("Hello world) } ``` Now reload the home page in your browser: [[images/error.png]] As you see errors are beautifully displayed directly in your browser. ## Preparing the application For our to do list application, we need a few actions and the corresponding URLs. Let’s start by defining the **routes**. Edit the `conf/routes` file: ``` # Home page GET / controllers.Application.index # Tasks GET /tasks controllers.Application.tasks POST /tasks controllers.Application.newTask POST /tasks/:id/delete controllers.Application.deleteTask(id: Long) ``` We create a route to list all tasks, and a couple of others to handle task creation and deletion. The route to handle task deletion defines a variable argument `id` in the URL path. This value is then passed to the `deleteTask` method that will create the `Action`. Now if you reload in your browser, you will see that Play cannot compile your `routes` file: [[images/routes.png]] This is because the new routes reference non-existent action methods. So let’s add them to the `Application.scala` file: ``` object Application extends Controller { def index = Action { Ok("Hello world") } def tasks = TODO def newTask = TODO def deleteTask(id: Long) = TODO } ``` As you see we use `TODO` to define our action implementations. Because we don’t want to write the action implementations yet, we can use the built-in `TODO` action that will return a `501 Not Implemented` HTTP response. You can try to access the [[http://localhost:9000/tasks]] to see that: [[images/todo.png]] Now the last thing we need to fix before starting the action implementation is the `index` action. We want it to automatically redirect to the tasks list page: ``` def index = Action { Redirect(routes.Application.tasks) } ``` As you can see, we use `Redirect` instead of `Ok` to specify a `303 See Other` HTTP response type. We also use the reverse router to get the URL needed to fetch the `tasks` actions. > **Note:** Read more about the [[Router and reverse router|ScalaRouting]]. ## Prepare the `Task` model Before continuing the implementation we need to define what a `Task` looks like in our application. Create a `case class` for it in the `app/models/Task.scala` file: ``` package models case class Task(id: Long, label: String) object Task { def all(): List[Task] = Nil def create(label: String) {} def delete(id: Long) {} } ``` We have also created a companion object to manage `Task` operations. For now we wrote a dummy implementation for each operation, but later in this tutorial we will write implementations that store the tasks in a relational database. ## The application template Our simple application will use a single web page that shows both the tasks list and the task creation form. Let’s modify the `index.scala.html` template for that: ``` @(tasks: List[Task], taskForm: Form[String]) @import helper._ @main("Todo list") {