Book Image

Instant Play Framework Starter

By : Daniel Dietrich
Book Image

Instant Play Framework Starter

By: Daniel Dietrich

Overview of this book

Play is a full-featured Java and Scala web framework for building modern, high-performance web applications. It is characterized by its simplicity and scalability. With its lightweight, stateless, and web-friendly architecture, Play focuses on developer experience to make web application development fun.Instant Play Framework Starter is the ideal companion to start developing web applications with Play. The building blocks of a typical web application are carefully designed following an on-going example.Instant Play Framework Starter starts with a quick setup and running a first sample. Then, the anatomy of a typical Play application is outlined. More features are added step by step to an example application. The result is the prototype of a highly scalable web application.The example is implemented in Java and in Scala. It consists of building blocks you will find in every Play application. In particular, you will learn how views are rendered with the template engine, how HTTP routes are used to define the navigation rules, and how to separate the application logic of controllers from the business logic of the model. This separation is the result of a careful application design, which makes it easy to add features like data binding and validation. Finally you will see how easy it is to adapt different database access libraries. Instant Play Framework Starter will help you to get started with Play and develop your first application. Packed with examples, it is easy to follow the design of a real-world application. You are able to compare the difference between a Java- and a Scala-based Play application and to decide which language fits your needs best. All topics covered in the book are described with the aim to serve as a reference for future web application development with Play.
Table of Contents (7 chapters)

Quick start – Creating your first Play application


Now that we have a working Play installation in place, we will see how easy it is to create and run a new application with just a few keystrokes.

Besides walking through the structure of our Play application, we will also look at what we can do with the command-line interface of Play and how fast modifications of our application are made visible.

Finally, we will take a look at the setup of integrated development environments (IDEs).

Step 1 – Creating a new Play application

So, let's create our first Play application. In fact, we create two applications, because Play comes with the APIs for Java and Scala, the sample accompanying us in this book is implemented twice, each in one separate language.

Tip

Please note that it is generally possible to use both languages in one project.

Following the DRY principle, we will show code only once if it is the same for the Java and the Scala application. In such cases we will use the play-starter-scala project.

First, we create the Java application. Open a command line and change to a directory where you want to place the project contents. Run the play script with the new command followed by the application name (which is used as the directory name for our project):

$ play new play-starter-java

We are asked to provide two additional information:

  • The application name, for display purposes. Just press the Enter key here to use the same name we passed to the play script. You can change the name later by editing the appName variable in play-starter-java/project/Build.scala.

  • The template we want to use for the application. Here we choose 2 for Java.


Repeat these steps for our Scala application, but now choose 1 for the Scala template. Please note the difference in the application name:

$ play new play-starter-scala

The following screenshot shows the output of the play new command:

On our way through the next sections, we will build an ongoing example step-by-step. We will see Java and Scala code side-by-side, so create both projects if you want to find out more about the difference between Java and Scala based Play applications.

Structure of a Play application

Physically, a Play application consists of a series of folders containing source code, configuration files, and web page resources. The play new command creates the standardized directory structure for these files:

/path/to/play-starter-scala
   |-app                source code
   | |-controllers      http request processors
   | |-views            templates for html files
   |-conf               configuration files
   |-project            sbt project definition
   |-public             folder containing static assets
   | |-images           images
   | |-javascripts      javascript files
   | |-stylesheets      css style sheets
   |-test               source code of test cases

During development, Play generates several other directories, which can be ignored, especially when using a version control system:

/path/to/play-starter-scala
   |-dist               releases in .zip format
   |-logs               log files
   |-project            THIS FOLDER IS NEEDED
   | |-project          but this...
   | |-target           ...and this can be ignored
   |-target             generated sources and binaries

There are more folders that can be found in a Play application depending on the IDE we use. In particular, a Play project has optional folders on more involved topics we do not discuss in this book. Please refer to the Play documentation for more details.

The app/ folder

The app/ folder contains the source code of our application. According to the MVC architectural pattern, we have three separate components in the form of the following directories:

  • app/models/: This directory is not generated by default, but it is very likely present in a Play application. It contains the business logic of the application, for example, querying or calculating data.

  • app/views/: In this directory we find the view templates. Play's view templates are basically HTML files with dynamic parts.

  • app/controllers/: This controllers contain the application specific logic, for example, processing HTTP requests and error handling.

The default directory (or package) names, models, views, and controllers, can be changed if needed.

The conf/ directory

The conf/ directory is the place where the application's configuration files are placed. There are two main configuration files:

  • application.conf: This file contains standard configuration parameters

  • routes – This file defines the HTTP interface of the application

The application.conf file is the best place to add more configuration options if needed for our application.

Configuration files for third-party libraries should also be put in the conf/ directory or an appropriate sub-directory of conf/.

The project/ folder

Play builds applications with the Simple Build Tool (SBT). The project/ folder contains the SBT build definitions:

  • Build.scala: This is the application's build script executed by SBT

  • build.properties: This definition contains properties such as the SBT version

  • plugins.sbt: This definition contains the SBT plugins used by the project

The public/ folder

Static web resources are placed in the public/ folder. Play offers standard sub-directories for images, CSS stylesheets, and JavaScript files. Use these directories to keep your Play applications consistent.

Create additional sub-directories of public/ for third-party libraries for a clear resource management and to avoid file name clashes.

The test/ folder

Finally, the test/ folder contains unit tests or functional tests. This code is not distributed with a release of our application.

Step 2 – Using the Play console

Play provides a command-line interface (CLI), the so-called Play console. It is based on the SBT and provides several commands to manage our application's development cycle.

Starting our application

To enter the Play console, open a shell, change to the root directory of one of our Play projects, and run the play script.

$ cd /path/to/play-starter-scala
$ play

On the Play console, type run to run our application in development (DEV) mode.

[play-starter-scala] $ run

Tip

Use ~run instead of run to enable automatic compilation of file changes. This gives us an additional performance boost when accessing our application during development and it is recommended by the author.

All console commands can be called directly on the command line by running play <command>. Multiple arguments have to be denoted in quotation marks, for example, play "~run 9001".

A web server is started by Play, which will listen for HTTP requests on localhost:9000 by default. Now open a web browser and go to this location.

The page displayed by the web browser is the default implementation of a new Play application.

To return to our shell, type the keys Ctrl + D to stop the web server and get back to the Play console.

Play console commands

Besides run, we typically use the following console commands during development:

  • clean: This command deletes cached files, generated sources, and compiled classes

  • compile: This command compiles the current application

  • test: This command executes unit tests and functional tests

We get a list of available commands by typing help play in the Play development console.

A release of an application is started with the start command in production (PROD) mode. In contrast to the DEV mode no internal state is displayed in the case of an error.

There are also commands of the play script, available only on the command line:

  • clean-all: This command deletes all generated directories, including the logs.

  • debug: This command runs the Play console in debug mode, listening on the JPDA port 9999. Setting the environment variable JDPA_PORT changes the port.

  • stop: This command stops an application that is running in production mode.

Closing the console

We exit the Play console and get back to the command line with the exit command or by simply typing the key Ctrl + D.

Step 3 – Modifying our application

We now come to the part that we love the most as impatient developers: the rapid development turnaround cycles. In the following sections, we will make some changes to the given code of our new application visible.

Fast turnaround – change your code and hit reload!

First we have to ensure that our applications are running. In the root of each of our Java and Scala projects, we start the Play console. We start our Play applications in parallel on two different ports to compare them side-by-side with the commands ~run and ~run 9001. We go to the browser and load both locations, localhost:9000 and localhost:9001.

Then we open the default controller app/controllers/Application.java and app/controllers/Application.scala respectively, which we created at application creation, in a text editor of our choice, and change the message to be displayed in the Java code:

public class Application extends Controller {
    public static Result index() {
        return ok(index.render("Look ma! No restart!"));
    }
}

and then in the Scala code:

object Application extends Controller {
  def index = Action {
    Ok(views.html.index("Look ma! No restart!"))
  }
}

Finally, we reload our web pages and immediately see the changes:

That's it. We don't have to restart our server or re-deploy our application. The code changes take effect by simply reloading the page.

Stripped down and optimized stack traces

If we make a change to our application that does not compile and refresh the browser, Play shows us exactly where the error is. Also, it provides us with a single message that tells us the cause of the compile error.

An example is shown as follows (only the Java code is shown here, feel free to play around):

public class Application extends Controller {
  
    public static Result index() {
        return "Look ma! No restart!";
    }
  
}

The previous change does not compile, and it leads to the following error:

Please note that these error messages are only shown in development mode. There are no internals exposed to the users when running in production mode.

Step 4 – Setting up your preferred IDE

Play takes care of automatically compiling modifications we make to our source code. That is why we don't need a full-blown IDE to develop Play applications. We can use a simple text editor instead.

However, using an IDE has many advantages, such as code completion, refactoring assistance, and debugging capabilities. Also it is very easy to navigate through the code. Therefore, Play has built-in project generation support for two of the most popular IDEs: IntelliJ IDEA and Eclipse.

IntelliJ IDEA

The free edition, IntelliJ IDEA Community, can be used to develop Play projects. However, the commercial release, IntelliJ IDEA Ultimate, includes Play 2.0 support for Java and Scala. Currently, it offers the most sophisticated features compared to other IDEs.

More information can be found here: http://www.jetbrains.com/idea and also here: http://confluence.jetbrains.com/display/IntelliJIDEA/Play+Framework+2.0

We generate the required IntelliJ IDEA project files by typing the idea command on the Play console or by running it on the command line:

$ play idea

We can also download the available source JAR files by running idea with-source=true on the console or on the command line:

$ play "idea with-source=true"

After that, the project can be imported into IntelliJ IDEA. Make sure you have the IDE plugins Scala, SBT, and Play 2 (if available) installed.

The project files have to be regenerated by running play idea every time the classpath changes, for example, when adding or changing project dependencies. IntelliJ IDEA will recognize the changes and reloads the project automatically. The generated files should not be checked into a version control system, as they are specific to the current environment.

Eclipse

Eclipse is also supported by Play. The Eclipse Classic edition is fine, which can be downloaded here: http://www.eclipse.org/downloads.

It is recommended to install the Scala IDE plugin, which comes up with great features for Scala developers and can be downloaded here: http://scala-ide.org. You need to download Version 2.1.0 (milestone) or higher to get Scala 2.10 support for Play 2.1.

Tip

A Play 2 plugin exists also for Eclipse, but it is in a very early stage. It will be available in a future release of the Scala IDE. More information can be found here: https://github.com/scala-ide/scala-ide-play2/wiki

The best way to edit Play templates with Eclipse currently is by associating HTML files with the Scala Script Editor. You get this editor by installing the Scala Worksheet plugin, which is bundled with the Scala IDE.

We generate the required Eclipse project files by typing the eclipse command on the Play console or by running it on the command line:

$ play eclipse

Analogous to the previous code, we can also download available source JAR files by running eclipse with-source=true on the console or on the command line:

$ play "eclipse with-source=true"

Also, don't check in generated project files for a version control system or regenerate project files if dependencies change. Eclipse (Juno) is recognizing the changed project files automatically.

Other IDEs

Other IDEs are not supported by Play out of the box. There are a couple of plugins, which can be configured manually. For more information on this topic, please consult the Play documentation.