Fun stuff

Getting Started with the Play Framework

Alex Hanschke
play-cover

What makes Play so special? In the first of a two part series, find out how you can tap into the latest trends with this innovative framework.

A brief introduction for Java Developers

These days, it’s hard to imagine a world without the Internet. Today’s applications are becoming increasingly connected; mash-ups of several services are becoming the norm. You have to wonder – where will we be in ten years?

If you’re reading this, chances are that you’re already familiar with the Java ecosystem. And with such a wide variety of web frameworks to choose from, why would you want to get to know yet another one? What it is about Play that makes it so special?

Why Play?

Play taps into current trends like cloud and big data. It fosters a stateless architecture and is RESTful by design. Developers can start implementing their applications with Play immediately: just save the code, hit refresh and you see all changes within a matter of seconds. Compare that to excessive application servers which you frequently have to restart before you can see your changes. Play comes with support for all major IDEs, although all you need is a simple text editor. Another major benefit is its type safety, which you won’t just notice in your controllers and models, but even in your views and routes! And if you’re a fan of LESS and CoffeeScript, you can make use of both directly in Play, which comes with a built-in compiler for both.

It’s easy to distinguish between component-based web frameworks like JSF or Vaadin and request-response-oriented frameworks such as the Play Framework (Play). While component-based variants try to hide everything that happens under the hood, request-response-based frameworks work much more closely with the HTTP protocol. And that means they give the developer several advantages which are lacking in component-based frameworks.

If you have a Java EE background, you will be amazed how much more productive you can be by using Play. You can easily kick off an application within a matter of seconds. This productivity gain makes it a natural choice for rapid prototyping, but it also makes a full-fledged solution for large-scale enterprise applications.

Ye Olde Bookstore

To discuss the features of Play in a broader context, let’s take a look at a sample application.

Most web frameworks will help you get your application up and running quickly. Render an input field, enter some data and submit it to the server, process it and render something back. It is the Hello World! for web frameworks. But that’s not quite what we want to do with Play. We want to see if this technology can fulfil our requirements.

When it starts getting more complex (think of validating a submitted password with the corresponding confirmation), things can easily get messy. And that’s only one of many examples. That’s why we’re not just going to get to know the framework, but we’ll also take a look at some of the common use cases and how to approach them with Play. You want to route a user back to the page they came from after a login? No problem. Store your data in the cloud? We’ll cover that too.

The example that we’ll be using is a bookstore. In order to keep things simple, we won’t make use of multiple features, such as shopping carts. Nevertheless, Play can easily support these use cases and once you get started you should be able to implement them on your own.

Installation

To get up and running, you’ll need to download the latest version of Play (2.1.0 when this was written) directly from the project site:

 http://download.playframework.org/releases/play-2.1.zip

Unpack the contents to a directory of your choice. Once this is completed, you should add the executable to your operating systems’ path variable, which under Mac OS can be achieved as follows:

$ export PATH=$PATH:/your/path/to/play-2.1.0

Listing 1.1 Adding the Play executable to your path on Mac OS

Now let’s see if everything works as expected by submitting play help in a shell. You should see a welcome message similar to the one shown in image 1.1.

Image 1.1 Welcome to Play!

Creating our first project

Now we’re ready to create our sample application. Choose a directory where you want the project to be located and then create it by running play new play-bookstore.

We confirm the name of the project by hitting [ENTER] and choose to create a simple Java application when asked. That’s it! Play has already generated a skeleton bookstore for us, so let’s have a look at what has been created.

Image 1.2 Bookstore project structure

During initialization Play already created all the directories we need. The resulting structure should look similar to the one shown in image 1.2. Let’s briefly walk through the directories one by one to see what they are good for.

The app directory contains our source files, such as controllers, the domain models and our views. In conf we can find the main application configuration and a file named routes. These routes describe the endpoints provided by our application in terms of URIs whereas each route is wired to a specific controller. Dependencies on other libraries and plugins are managed in the project directory. In Build.scala we can declare each dependency using Scala syntax. You should be able to grasp the structure even without prior Scala knowledge. Our public assets are served from the public directory. Here we keep stylesheets, JavaScripts and images. Play comes with native support for LESS CSS (http://lesscss.org/) and CoffeeScript (http://coffeescript.org/). So we will find the corresponding files here as well. Last but not least the test directory keeps track of our tests of all kind, such as unit and integration tests.

Enough said – let’s run it!

What Play has created is executable through play run. Play compiles all of the code and starts up a Netty server, which serves our bookstore. When we run Play like this, it is started in development mode, meaning Play will wait for an initial request before starting the application, as opposed to the production mode where the application is started immediately. So go ahead and open http://localhost:9000 in your browser and you should see a screen similar to the one shown in image 1.3.

Image 1.3 Your new application is ready

If you can’t bind the server to the default port 9000, you can also specify an alternative port by passing it as an argument: play “run 8080” (mind the quotes).

Request lifecycle

Before we dig any deeper, here’s what happened when you opened the application in your browser:

  1. Your browser requested the resource under “/” – the application root.

  2. Play figured out the handler for this request by looking up the aforementioned routes file.

  3. The action to invoke is called index and it is defined by a controller named Application.

  4. In index, the view to be rendered is chosen and sent back to your browser.

  5. The view you eventually saw is defined in a file named index.scala.html.

While the application is running, we can now change some values, hit reload and see the browser picking up on these changes immediately.

Open the Application class located under app/controllers. In the index method, change the text to another value, save your changes and refresh the page in the browser. You should now see the new value. As you can see, Play recompiles your application on the fly whenever it detects changes.

The basics of HTTP

When working with web frameworks it is helpful if you are familiar with the basics of the Hypertext Transfer Protocol (HTTP). While there are plenty of frameworks in the Java ecosystem that do their best to hide the low-level HTTP operations behind a component-based API, Play follows a request-response-based approach, similar to how Servlets work.

HTTP supports a couple of verbs, four of which are of major interest when working with Play. They are GET, POST, UPDATE and DELETE. When you open a particular address in your browser, say http://techdev.de, the browser performs a GET request, i.e. it requests to read data from the server. POST is used whenever we request the creation of a new resource on the server under the corresponding URI. For example, this is the case when we want to create a new book based on the input provided by a user. Likewise, the two remaining verbs are used to update existing resources on the server, or to delete them respectively.

RESTful design

Building directly on HTTP, REpresentational State Transfer (REST) follows the idea that everything in an application can be exported as a resource. Resources can be read, manipulated and deleted using pure HTTP. Furthermore, resources can be represented in arbitrary formats. For example, a book resource can be represented as an HTML page or in JSON. Play encourages the use of RESTful design, so this is what it might look like in your application:

GET /books

GET /books/1234.xml

POST /books

Listing 1.2 Defining URIs to access book resources

The first request attempts to read a collection of book resources, whereas the second request reads a specific book resource represented in XML. The last request can be used to create a new book resource with the content submitted with the request.

Depending on the Accept header in our request, we can request a particular representation from the server. For example with Accept: application/xml we specify that we want to read the XML representation of a resource. A client can specify several representations as a fallback mechanism for the server, a process which is also referred to as content negotiation.

Thus, a resource can have multiple representations in a RESTful application.

Apart from the welcome page you have just seen, Play also deploys an offline documentation, which is accessible at http://localhost:9000/@documentation while the server is running. This is pretty handy if you are developing offline and need to access the documentation or the JavaDocs.

Preparing the editor

Now it’s time to get our feet wet and start developing, so let’s choose an appropriate editor and have a look at the development workflow.

Play supports all major IDEs, but you might as well go for a simple text editor such as Sublime Text 2 (http://www.sublimetext.com/2) for development. However, as it is so widely adopted, we will use Eclipse. To create the required project files, open a shell in your actual project root and run play eclipse.

In Eclipse, choose File | Import… | Existing projects into workspace, browse to your project directory and confirm the import. Play expects all files to be encoded as UTF-8 so whatever tool you choose for development, make sure that UTF-8 encoding is the default. Eclipse usually has this set already, but you can verify it by checking that Text File Encoding is properly set under Project | Properties | Resource.

Well done! Now you’re ready to dive straight into the development!

This is an excerpt from the forthcoming Developer.Press title Getting Started with Play. In the next chapter of the book, Alex walks us through the domain model and the persistence layer.

About the author

Alexander Hanschke holds a Master’s in Business Informatics from the University of Mannheim. While graduating, he joined the Karlsruhe-based consultancy COINOR AG where he helped customers from the financial sector build large-scale enterprise applications using Java EE. After working with COINOR for two years, Alex decided to step out and build his own company, techdev Solutions. He now helps clients across all industries build cloud-enabled applications. He has been developing applications in the Play Framework for two years and recently spoke on this topic at a JAX Conference.

Author
Comments
comments powered by Disqus