Chapter 1. Introduction to Play 2

This chapter covers

  • Defining the Play framework
  • Explaining high-productivity web frameworks
  • Why Play supports both Java and Scala
  • Why Scala needs the Play framework
  • Creating a minimal Play application

Play isn’t a Java web framework. Java’s involved, but that isn’t the whole story. Although the first version of Play was written in the Java language, it ignored the conventions of the Java platform, providing a fresh alternative to excessive enterprise architectures. Play wasn’t based on Java Enterprise Edition APIs and it wasn’t made for Java developers. Play was made for web developers.

Play wasn’t just written for web developers; it was written by web developers, who brought high-productivity web development from modern frameworks like Ruby on Rails and Django to the JVM. Play is for productive web developers.

Play 2 is written in Scala, which means that not only do you get to write your web applications in Scala, but you also benefit from increased type safety throughout the development experience.

Play isn’t only about Scala and type safety. An important aspect of Play is its usability and attention to detail, which results in a better developer experience (DX). When you add this to higher developer productivity and more elegant APIs and architectures, you get a new emergent property: Play is fun.

1.1. What Play is

Play makes you more productive. Play is also a web framework whose HTTP interface is simple, convenient, flexible, and powerful. Most importantly, Play improves on the most popular non-Java web development languages and frameworks—PHP and Ruby on Rails—by introducing the advantages of the Java Virtual Machine (JVM).

1.1.1. Key features

A variety of features and qualities makes Play productive and fun to use:

  • Declarative application URL scheme configuration
  • Type-safe mapping from HTTP to an idiomatic Scala API
  • Type-safe template syntax
  • Architecture that embraces HTML5 client technologies
  • Live code changes when you reload the page in your web browser
  • Full-stack web framework features, including persistence, security, and internationalization

We’ll get back to why Play makes you more productive, but first let’s look a little more closely at what it means for Play to be a full-stack framework, as shown in figure 1.1. A full-stack framework gives you everything you need to build a typical web application.

Figure 1.1. Play framework stack

Being “full-stack” isn’t only a question of functionality, which may already exist as a collection of open source libraries. After all, what’s the point of a framework if these libraries already exist and provide everything you need to build an application? The difference is that a full-stack framework also provides a documented pattern for using separate libraries together in a certain way. If you have this, as a developer, you know that you’ll be able to make the separate components work together. Without this, you never know whether you’re going to end up with two incompatible libraries, or a badly designed architecture.

When it comes to building a web application, what this all means is that the common tasks are directly supported in a simple way, which saves you time.

1.1.2. Java and Scala

Play supports Java, and it’s the best way to build a Java web application. Java’s success as a programming language, particularly in enterprise software development, has enabled Play to quickly build a large user community. Even if you’re not planning to use Play with Java, you still get to benefit from the size of the wider Play community. Besides, a large segment of this community is now looking for an alternative to Java.

But recent years have seen the introduction of numerous JVM languages that provide a modern alternative to Java, usually aiming to be more type-safe, resulting in more concise code, and supporting functional programming idioms, with the ultimate goal of allowing developers to be more expressive and productive when writing code. Scala is currently the most evolved of the new statically typed JVM languages, and it’s the second language that Play supports.

Play 2 for Java

If you’re also interested in using Java to build web applications in Play, you should take a look at Play 2 for Java, which was written at the same time as this book. The differences between Scala and Java go beyond the syntax, and the Java book isn’t a copy of this book with the code samples in Java. Play 2 for Java is more focused on enterprise architecture integration than is this book, which introduces more new technology.

Having mentioned Java and the JVM, it also makes sense to explain how Play relates to the Java Enterprise Edition (Java EE) platform, partly because most of our web development experience is with Java EE. This isn’t particularly relevant if your web development background is with PHP, Rails, or Django, in which case you may prefer to skip the next section and continue reading with section 1.2.

1.1.3. Play isn’t Java EE

Before Play, Java web frameworks were based on the Java Servlet API, the part of the Java Enterprise Edition stack that provides the HTTP interface. Java EE and its architectural patterns seemed like a good idea, and brought some much-needed structure to enterprise software development. But this turned out to be a bad idea, because structure came at the cost of additional complexity and low developer satisfaction. Play is different, for several reasons.

Java’s design and evolution is focused on the Java platform, which also seemed like a good idea to developers who were trying to consolidate various kinds of software development. From a Java perspective, the web is only another external system. The Servlet API, for example, adds an abstraction layer over the web’s own architecture that provides a more Java-like API. Unfortunately, this is a bad idea, because the web is more important than Java. When a web framework starts an architecture fight with the web, the framework loses. What we need instead is a web framework whose architecture embraces the web’s, and whose API embraces HTTP.

Lasagna architecture

One consequence of the Servlet API’s problems is complexity, mostly in the form of too many layers. This is the complexity caused by the API’s own abstraction layers, compounded by the additional layer of a web framework that provides an API that’s rich enough to build a web application, as shown in figure 1.2.

Figure 1.2. Java EE “lasagna” architecture compared to Play’s simplified architecture

The Servlet API was originally intended to be an end-user API for web developers, using Servlets (the name for controller Java classes), and JavaServer Pages (JSP) view templates. When new technologies eventually superseded JSP, they were layered on top, instead of being folded back into Java EE, either as updates to the Servlet API or as a new API. With this approach, the Servlet API becomes an additional layer that makes it harder to debug HTTP requests. This may keep the architects happy, but it comes at the cost of developer productivity.

The JSF non-solution

This lack of focus on productive web development is apparent within the current state of Java EE web development, which is now based on JavaServer Faces (JSF). JSF focuses on components and server-side state, which also seemed like a good idea, and gave developers powerful tools for building web applications. But again, it turned out that the resulting complexity and the mismatch with HTTP itself made JSF hard to use productively.

Java EE frameworks such as JBoss Seam did an excellent job at addressing early deficiencies in JSF, but only by adding yet another layer to the application architecture. Since then, Java EE 6 has improved the situation by addressing JSF’s worst shortcomings, but this is certainly too little, too late.

Somewhere in the history of building web applications on the JVM, adding layers became part of the solution without being seen as a problem. Fortunately for JVM web developers, Play provides a redesigned web stack that doesn’t use the Servlet API and works better with HTTP and the web.

1.2. High-productivity web development

Web frameworks for web developers are different. They embrace HTTP and provide APIs that use HTTP’s features instead of trying to hide HTTP, in the same way that web developers build expertise in the standard web technologies—HTTP, HTML, CSS, and JavaScript—instead of avoiding them.

1.2.1. Working with HTTP

Working with HTTP means letting the application developer make the web application aware of the different HTTP methods, such as GET, POST, PUT, and DELETE. This is different than putting an RPC-style layer on top of HTTP requests, using remote procedure call URLs like /updateProductDetails in order to tell the application whether you want to create, read, update, or delete data. With HTTP it’s more natural to use PUT / product to update a product and GET /product to fetch it.

Embracing HTTP also means accepting that application URLs are part of the application’s public interface, and should therefore be up to the application developer to design instead of being fixed by the framework.

This approach is for developers who not only work with the architecture of the World Wide Web, instead of against it, but may have even read it.[1]

1 Architecture of the World Wide Web, Volume One, W3C, 2004 (www.w3.org/TR/webarch/).

In the past, none of these web frameworks were written in Java, because the Java platform’s web technologies failed to emphasize simplicity, productivity, and usability. This is the world that started with Perl (not Lisp, as some might assume), was largely taken over by PHP, and in more recent years has seen the rise of Ruby on Rails.

1.2.2. Simplicity, productivity, and usability

In a web framework, simplicity comes from making it easy to do simple things in a few lines of code, without extensive configuration. A Hello World in PHP is a single line of code; the other extreme is JavaServer Faces, which requires numerous files of various kinds before you can even serve a blank page.

Productivity starts with being able to make a code change, reload the web page in the browser, and see the result. This has always been the norm for many web developers, whereas Java web frameworks and application servers often have long build-redeploy cycles. Java hot-deployment solutions exist, but they aren’t standard and come at the cost of additional configuration. Although there’s more to productivity, this is what matters most.

Usability is related to developer productivity, but also to developer happiness. You’re certainly more productive if it’s easier to get things done, no matter how smart you are, but a usable framework can be more than that—a joy to use. Fun, even.

1.3. Why Scala needs Play

Scala needs its own high-productivity web framework. These days, mainstream software development is about building web applications, and a language that doesn’t have a web framework suitable for a mainstream developer audience remains confined to niche applications, whatever the language’s inherent advantages.

Having a web framework means more than being aware of separate libraries that you could use together to build a web application; you need a framework that integrates them and shows you how to use them together. One of a web framework’s roles is to define a convincing application architecture that works for a range of possible applications. Without this architecture, you have a collection of libraries that might have a gap in the functionality they provide or some fundamental incompatibility, such as a stateful service that doesn’t play well with a stateless HTTP interface. What’s more, the framework decides where the integration points are, so you don’t have to work out how to integrate separate libraries yourself.

Another role a web framework has is to provide coherent documentation for the various technologies it uses, focusing on the main web application use cases, so that developers can get started without having to read several different manuals. For example, you hardly need to know anything about the JSON serialization library that Play uses to be able to serve JSON content. All you need to get started is an example of the most common use case and a short description about how it works.

Other Scala web frameworks are available, but these aren’t full-stack frameworks that can become mainstream. Play takes Scala from being a language with many useful libraries to being a language that’s part of an application stack that large numbers of developers will use to build web applications with a common architecture. This is why Scala needs Play.

1.4. Type-safe web development—why Play needs Scala

Play 1.x used bytecode manipulation to avoid the boilerplate and duplication that’s typical when using Java application frameworks. But this bytecode manipulation seems like magic to the application developer, because it modifies the code at runtime. The result is that you have application code that looks like it shouldn’t work, but which is fine at runtime.

The IDE is limited in how much support it can provide, because it doesn’t know about the runtime enhancement either. This means that things like code navigation don’t seem to work properly, when you only find a stub instead of the implementation that’s added at runtime.

Scala has made it possible to reimplement Play without the bytecode manipulation tricks that the Java version required in Play 1.x. For example, Play templates are Scala functions, which means that view template parameters are passed normally, by value, instead of as named values to which templates refer.

Scala makes it possible for web application code to be more type-safe. URL routing and template files are parsed using Scala, with Scala types for parameters.

To implement a framework that provides equivalent idiomatic APIs in both Java and Scala, you have to use Scala. What’s more, for type-safe web development, you also need Scala. In other words, Play needs Scala.

1.5. Hello Play!

As you’d expect, it’s easy to do something as simple as output “Hello world!” All you need to do is use the Play command that creates a new application, and write a couple of lines of Scala code. To begin to understand Play, you should run the commands and type the code, because only then will you get your first experience of Play’s simplicity, productivity, and usability.

The first step is to install Play. This is unusual for a JVM web framework, because most are libraries for an application that you deploy to a Servlet container that you’ve already installed. Play is different. Play includes its own server and build environment, which is what you’re going to install.

1.5.1. Getting Play and setting up the Play environment

Start by downloading the latest Play 2 release from http://playframework.org. Extract the zip archive to the location where you want to install Play—your home directory is fine.

Play’s only prerequisite is a JDK—version 6 or later—which is preinstalled on Mac OS X and Linux. If you’re using Windows, download and install the latest JDK.

Mac users can use Homebrew

If you’re using Mac OS X, you could also use Homebrew to install Play 2. Use the command brew install play to install, and Homebrew will download and extract the latest version, and take care of adding it to your path, too.

Next, you need to add this directory to your PATH system variable, which will make it possible for you to launch Play by typing the play command. Setting the PATH variable is OS-specific.

  • Mac OS XOpen the file /etc/paths in a text editor, and add a line consisting of the Play installation path.
  • LinuxOpen your shell’s start-up file in a text editor. The name of the file depends on which shell you use; for example, .bashrc for bash or .zshrc for zsh. Add the following line to the file: PATH="$PATH":/path/to/play, substituting your Play installation path after the colon.
  • Windows XP or laterOpen the command prompt and execute the command setx PATH "%PATH%;c:path oplay" /m substituting your Play installation path after the semicolon.

Now that you’ve added the Play directory to your system path, the play command should be available on the command line. To try it out, open a new command-line window, and enter the play command. You should get output similar to this:

       _            _
 _ __ | | __ _ _  _| |
| '_ | |/ _' | || |_|
|  __/|_|\____|\__ (_)
|_|            |__/

play! 2.1.1, http://www.playframework.org

This is not a play application!

Use `play new` to create a new Play application in the
current directory, or go to an existing application
and launch the development console using `play`.

You can also browse the complete documentation at
http://www.playframework.org.

As you can see, the play command by itself only did two things: output an error message (This is not a play application!) and suggest that you try the play new command instead. This is a recurring theme when using Play: when something goes wrong, Play will usually provide a useful error message, guess what you’re trying to do, and suggest what you need to do next. This isn’t limited to the command line; you’ll also see helpful errors in your web browser later on.

For now, let’s follow Play’s suggestion and create a new application.

1.5.2. Creating and running an empty application

A Play application is a directory on the filesystem that contains a certain structure that Play uses to find configuration, code, and any other resources it needs. Instead of creating this structure yourself, you use the play new command, which creates the required files and directories.

Enter the following command to create a Play application in a new subdirectory called hello:

play new hello

When prompted, confirm the application name and select the Scala application template, as listing 1.1 shows:

Listing 1.1. Command-line output when you create a new Play application
$ play new hello
       _            _
 _ __ | | __ _ _  _| |
| '_ | |/ _' | || |_|
|  __/|_|\____|\__ (_)
|_|            |__/


play! 2.1, http://www.playframework.org

The new application will be created in /src/hello

What is the application name?
> hello

Which template do you want to use for this new application?

  1 - Create a simple Scala application
  2 - Create a simple Java application

> 1
OK, application hello is created.

Have fun!

The first time you do this, the build system will download some additional files (not shown). Now you can run the application.

Listing 1.2. Command-line output when you run the application
$ cd hello
$ play run
[info] Loading global plugins from /Users/peter/.sbt/plugins/project
[info] Loading global plugins from /Users/peter/.sbt/plugins
[info] Loading project definition from /src/hello/project
[info] Set current project to hello (in build file:/src/hello/)

--- (Running the application from SBT, auto-reloading is enabled) ---

[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0%0:9000

(Server started, use Ctrl+D to stop and go back to the console...)

As when creating the application, the build system will download some additional files the first time.

1.5.3. Play application structure

The play new command creates a default application with a basic structure, including a minimal HTTP routing configuration file, a controller class for handling HTTP requests, a view template, jQuery, and a default CSS stylesheet, as listing 1.3 shows.

Listing 1.3. Files in a new Play application
.gitignore
app/controllers/Application.scala
app/views/index.scala.html
app/views/main.scala.html
conf/application.conf
conf/routes
project/build.properties
project/Build.scala

project/plugins.sbt
public/images/favicon.png
public/javascripts/jquery-1.7.1.min.js
public/stylesheets/main.css
test/ApplicationSpec.scala
test/IntegrationSpec.scala

This directory structure is common to all Play applications. The top-level directories group the files as follows:

  • appApplication source code
  • confConfiguration files and data
  • projectProject build scripts
  • publicPublicly accessible static files
  • testAutomated tests

The play run command starts the Play server and runs the application.

Use ~run to compile changed files immediately

If you start your application with the run command, Play will compile your changes when it receives the next HTTP request. To start compilation sooner, as soon as the file has changed, use the ~run command instead.

1.5.4. Accessing the running application

Now that the application is running, you can access a default welcome page at http://localhost:9000/, as figure 1.3 shows.

Figure 1.3. The default welcome page for a new Play application

This is already a kind of Hello World example—it shows a running application that outputs something, which allows you to see how things fit together. This is more than a static HTML file that tells you that the web server is running. Instead, this is the minimal amount of code that can show you the web framework in action. This makes it easier to create a Hello World example than it would be if you had to start with a completely blank slate—an empty directory that forces you to turn to the documentation each time you create a new application, which probably isn’t something you’ll do every day.

Leaving our example application at this stage would be cheating, so we need to change the application to produce the proper output. Besides, it doesn’t say “hello world” yet.

1.5.5. Add a controller class

Edit the file app/controllers/Application.scala and replace the Application object’s index method with the following:

def index = Action {
  Ok("Hello world")
}

This defines an action method that generates an HTTP OK response with text content. Now http://localhost:9000/ serves a plain-text document containing the usual output.

This works because of the line in the conf/routes HTTP routing configuration file that maps GET / HTTP requests to a method invocation:

GET /   controllers.Application.index()

1.5.6. Add a compilation error

The output is more interesting if you make a mistake. In the action method, remove the closing quote from "Hello world", save the file, and reload the page in your web browser. You’ll get a friendly compilation error, as figure 1.4 shows.

Figure 1.4. Compilation errors are shown in the web browser, with the relevant source code highlighted.

Fix the error in the code, save the file, and reload the page again. It’s fixed. Play dynamically reloads changes, so you don’t have to manually build the application every time you make a change.

1.5.7. Use an HTTP request parameter

This is still not a proper web application example, because we didn’t use HTTP or HTML yet. To start with, add a new action method with a string parameter to the controller class:

def hello(name: String) = Action {
  Ok("Hello " + name)
}

Next, add a new line to the conf/routes file to map a different URL to your new method, with an HTTP request parameter called n:

GET /hello   controllers.Application.hello(n: String)

Now open http://localhost:9000/hello?n=Play! and you can see how the URL’s query string parameter is passed to the controller action. Note that the query string parameter n matches the parameter name declared in the routes file, not the hello action method parameter.

1.5.8. Add an HTML page template

Finally, to complete this first example, you need an HTML template, because you usually use web application frameworks to generate web pages instead of plain-text documents. Create the file app/views/hello.scala.html with the following content:

@(name:String)
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello</title>
  </head>
  <body>
    <h1>Hello <em>@name</em></h1>
  </body>
</html>

This is a Scala template. The first line defines the parameter list—a name parameter in this case—and the HTML document includes an HTML em tag whose content is a Scala expression—the value of the name parameter. A template is a Scala function definition that Play will convert to normal Scala code and compile. Section 3.5.4 explains how templates become Scala functions in more detail.

To use this template, you have to render it in the hello action method to produce its HTML output. Once Play has converted the template to a Scala object called views .html.hello, this means calling its apply method. You then use the rendered template as a String value to return an Ok result:

def hello(name: String) = Action {
  Ok(views.html.hello(name))
}

Reload the web page—http://localhost:9000/hello?n=Play!—and you’ll see the formatted HTML output.

1.6. The console

Web developers are used to doing everything in the browser. With Play, you can also use the Play console to interact with your web application’s development environment and build the system. This is important for both quick experiments and automating things.

To start the console, run the play command in the application directory without an additional command:

play

If you’re already running a Play application, you can type Control+D to stop the application and return to the console.

The Play console gives you a variety of commands, including the run command that you saw earlier. For example, you can compile the application to discover the same compilation errors that are normally shown in the browser, such as the missing closing quotation mark that you saw earlier:

[hello] $ compile
[info] Compiling 1 Scala source to target/scala-2.10/classes...
[error] app/controllers/Application.scala:9: unclosed string literal
[error]   Ok("Hello world)
[error]      ^
[error] .../controllers/Application.scala:10: ')' expected but '}' found
[error] }
[error] ^
[error] two errors found
[error] (compile:compile) Compilation failed
[error] Total time: 2 s, completed Jun 16, 2013 11:40:29 AM
[hello] $

You can also start a Scala console (after fixing the compilation error), which gives you direct access to your compiled Play application:

[hello] $ console
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.10.0
(Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_37).
Type in expressions to have them evaluated.
Type :help for more information.

scala>

Now that you have a Scala console with your compiled application, you can do things like render a template, which is a Scala function that you can call:

scala> views.html.hello.render("Play!")
res0: play.api.templates.Html =

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello</title>
  </head>
  <body>
    <h1>Hello <em>Play!</em></h1>
  </body>
</html>

We just rendered a dynamic template in a web application that isn’t running. This has major implications for being able to test your web application without running a server.

1.7. Summary

Play was built by web developers, for web developers—taking good ideas from existing high-productivity frameworks, and adding the JVM’s power and rich ecosystem. The result is a web framework that offers productivity and usability as well as structure and flexibility. After starting with a first version implemented in Java, Play has now been reimplemented in Scala, with more type safety throughout the framework. Play gives Scala a better web framework, and Scala gives Play a better implementation for both Scala and Java APIs.

As soon as you start writing code, you go beyond Play’s background and its feature list to what matters: the user experience, which determines what it’s like to use Play. Play achieves a level of simplicity, productivity, and usability that means you can look forward to enjoying Play and, we hope, the rest of this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset