Chapter 1. An introduction to Play

This chapter covers

  • What the Play framework is
  • What high-productivity web frameworks are about
  • Why Play supports both Java and Scala
  • Reactive programming
  • Play 2 enterprise features
  • What a minimal Play application looks like

Play isn’t really a Java web framework. Java’s involved, but that isn’t the whole story.

The first version of Play may have been written in the Java language, but it also ignored the conventions of the Java platform, providing a fresh alternative to excessive enterprise architectures. Play was not based on Java Enterprise Edition APIs and made for Java developers; Play is for web developers.

Play wasn’t written for web developers, it was written by web developers, and they 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, but that doesn’t mean you have to write your web applications in Scala or even know anything about Scala. This is because Play 2 comes with a complete Java API, giving you the option to pick the language that suits you best. If you’ve used Play 1.x before, you’ll notice that the API has become more type-safe.

Play isn’t about Scala and type safety, either. An important aspect of Play is the usability and attention to detail that 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 is fun. 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 make Play productive and fun to use:

  • Simplicity
  • Declarative application URL scheme configuration
  • Type-safe mapping from HTTP to an idiomatic Scala or Java 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
  • Support for event-driven, resilient, and scalable applications

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. A full-stack framework gives you everything you need to build a typical web application, as illustrated in figure 1.1.

Figure 1.1. Play framework stack

Being “full stack” is not 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 already 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, and therefore provides confidence that a developer can make the separate components work together. Without this, you never know whether you’re going to end up instead 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 is in fact the best way to build a Java web application. Java’s success as a programming language, particularly in enterprise software development, means that Play 1.x has been able to quickly build a large user community. If you’re planning to use Play with Java, you particularly get to benefit from this community’s size.

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 support for 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. Scala is meant (and proven) to be a scalable language, hence the name. Play 2 takes full advantage of the scalability that Scala offers, which means your Java applications will get these benefits, too.

Scalability is one of the major features of Play: it allows you to easily create highly scalable web applications. Scalability can mean a lot of different things, and throughout the book you’ll see examples of how Play enables you to scale both horizontally and vertically. Most of this is thanks to Play’s stateless nature, but also its foundation of Scala (and Akka), which enabled the developers of the framework to provide concurrent and nonblocking request processing. It also enabled developers to support applications in an event-driven way without sacrificing scalability. Nowadays, applications need to react to events and display live feeds rather than batch process during the night. Play was conceived with this perspective in mind. We’ll talk more about this subject in the reactive programming section in this chapter.

Our sister book: Play for Scala

If you’re also interested in using Play to build web applications in Scala, then you should look at Play for Scala, which was written at the same time as this book. The differences between Scala and Java go beyond the syntax, and the Scala book is much more than a copy of this book with code samples in Scala. Play for Scala is focused on the idiomatic use of the Scala language with Play 2.

1.1.3. Play is not Java EE

Before Play, Java web frameworks were based on the Java Servlet API, the part of the Java Enterprise Edition (Java EE) stack that provides the HTTP interface. Java EE and its architectural patterns seemed like a really good idea, and brought some much-needed structure to enterprise software development. But this turned out to be a really bad idea, because structure came at the cost of additional complexity and low developer satisfaction. Play is different, for several reasons, which we’ll detail later in this chapter. The biggest difference between Java EE and Play is simplicity. Play focuses on providing simplicity to developers so that they can focus on their business problems and not on the framework itself. In contrast, Java EE used to be quite complex.

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, is an abstraction layer over the web’s own architecture that provides a more Java-like API. Unfortunately, this turned out to be a bad idea as well, 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.

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, instead of having an RPC-style layer on top of HTTP requests in order to tell the application whether you want to create, update, or delete data. It 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 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 who may have even read it.[1]

1 Architecture of the World Wide Web, Volume One, W3C, 2004 (http://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 are not standard and come at the cost of additional configuration. Although there is 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 simply get things done, no matter how smart you are, but a usable framework can be more than that; it can be a joy to use. Fun, even.

1.3. Reactive programming

Play has unique features in the Java world. It allows applications to be nonblocking, asynchronous, and reactive. But what does this mean exactly? As we’ll see in chapter 4, application requirements have changed dramatically in recent years. Today applications are deployed on everything from mobile devices to cloud-based clusters. User expectations are high: applications need to respond in milliseconds, and no downtime is allowed. Data needs are expanding into the petabytes.

Before Play and similar frameworks, scaling was achieved through buying larger servers, and concurrent processing via multithreading. Applications were running inside managed servers and containers. Applications were making little use of the multiple processors made available to them.

Reactive programming is about providing an architecture that allows developers to build systems that are event-driven, scalable, resilient, and responsive: delivering highly responsive user experiences with a real-time feel, backed by a scalable and resilient application stack, ready to be deployed on multicore and cloud computing architectures. The Play framework has these goals in mind and attempts to fulfill them.

Let’s review each of the goals.

1.3.1. Event-driven

An application based on asynchronous communication implements a loosely coupled design. The sender and recipient can be implemented without regard to the details of how the events are propagated, allowing the interfaces to focus on the communication. Because the recipient of asynchronous communication can remain dormant until an event occurs or a message is received, an event-driven approach can make efficient use of existing resources, allowing large numbers of recipients to share a single hardware thread. A nonblocking application that is under heavy load can have lower latency and higher throughput than a traditional application based on blocking synchronization.

1.3.2. Scalable

A scalable application is one that can be expanded according to its demand. This can be achieved by adding elasticity to the application by adding or removing application nodes (servers or CPUs, for example). The architecture should handle elasticity without redesigning or rewriting the application. Cloud-computing environments tend to provide near to perfect elasticity to your application. An event-driven system provides the foundation for scalability because it provides loose coupling and location independence between components and subsystems.

1.3.3. Resilient

Application downtime nowadays is not allowed, and business users expect 24/7 uptime. If an application component crashes for one reason or another, the rest of the application should still work as expected. This means that each component needs to be isolated from other components’ failure. The event-driven model has the necessary primitives to realize this model of failure management.

1.3.4. Responsive

Responsive applications are real-time and collaborative applications. Today, businesses try to engage their customers more and more. They are also trying to be really responsive to any customer feedback. Applications should therefore be real time and allow you to react to any customer feedback. Responsive applications are about real-time interaction between the different users. One example is Google Docs, which enables users to edit documents collaboratively in real time—allowing them to see each other’s edits and comments live as they’re made.

Now that we know all about Play’s goals, let’s see how Play fits at work. Not all enterprise applications have to be reactive.

1.4. Play 2 enterprise features

Play is also adapted to an enterprise environment. Mainly it satisfies the following enterprise requirements.

1.4.1. Simplicity

Play provides a clean component model that makes it easy to build scalable web applications that are testable. Simplicity has always been the Play framework’s strong point and is important in an enterprise context. Developers need to concentrate on their business problems at hand and not on the framework. The framework should help them and not be in the way. The Play framework’s first focus was always on simplicity. Simplicity doesn’t mean a simple application: quite the opposite. Play provides simple but efficient building blocks, allowing development of complex applications. Simplicity is important in an enterprise context because it allows wide adoption of the framework within the company by lowering the barrier of entrance.

1.4.2. Traditional data access

Play provides all the necessary data access to enterprise data. This usually means accessing several databases from within one application. With Play, by default, you can access those data via JPA, the standard Java EE Java Persistence API, or via Ebean. JPA is currently widely adopted in the enterprise, so developers won’t feel lost. Ebean is quite similar to JPA, but tries to be stateless with data access. You can also use Play’s JDBC helpers if you want more low-level data access.

1.4.3. Flexibility

Play is flexible: almost everything is pluggable, configurable, and customizable. This means it’s easy to change or extend any part of the framework. For example, you can rewrite the way Play handles request parsing. You can also plug your own logic inside the framework lifecycle, for example, before your application is started. Play is modular from the start. The Play framework is composed of several modules: core, jdbc, jpa, json, cache, and more.

1.4.4. Integration

Because Play is so flexible, it’s easy to integrate a Play framework application with other (legacy) systems. For example, you can easily integrate with an LDAP server to authenticate using third-party libraries and make calls into it. Play provides hooks to plug in your custom code throughout the framework. Out of the box, you can integrate with any existing database through JPA, JDBC, or you can add your own persistence layer.

Through the use of modules, Play provides even more ways to integrate with other systems. As an enterprise, you can write your own reusable modules to integrate with legacy systems.

1.4.5. Large-team applications

Play is also made to work with large teams; it’s possible to set up a project with multiple subprojects. The project can then be split among multiple teams with each team working on a subproject. Play provides support to manage those subprojects so they’re automatically built and updated when releasing the application: applications can depend on other applications, and Play allows you to declare that and make it explicit.

1.4.6. Security

Play provides the backbone for handling authentication and authorization. As a developer, you need to hook into the Play security mechanism and provide the implementation that authenticates against your enterprise servers. Play goes even a step further, because it allows you to completely rewrite that part as well if the model doesn’t fit your enterprise security model. Because Play stays simple, it’s not difficult to plug in your own mechanism.

1.4.7. Modularity

Play is modular by design and allows developers to build simple, reusable pieces of software. Stacking up those reusable pieces makes it possible to build quite complex and robust systems. Each team can concentrate on a piece of the puzzle and each piece of the puzzle can be tested independently. Reusable modules can be shared among developers and enterprise departments. For example, an enterprise can build its authentication module once and make it available as a module to be reused by all applications.

After this Play framework overview, it’s now time to experience simplicity!

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 Java code. To begin to understand Play, you should run the command and type the code, because only then will you get your first experience of Play’s simplicity, productivity, and usability. But to do that, you’ll need to have Play installed. We’ll get to that in a minute.

First, it’s interesting to talk about why there even is an installation step with Play 2. Most web frameworks in the Java world are libraries that you add to your project and bootstrap with some configuration file (such as web.xml) or boilerplate code to run in a Servlet container or application server. With these frameworks, there is no install step. Play is more than a library; it provides a complete tool suite, including a web server and a build tool.

Installing Play is easy; here’s how.

1.5.1. Installing Play

First, download Play 2.2 from the web site at http://playframework.org. Extract the .zip file to the location at which you want to install Play 2 (your home directory is fine). Next, you need to add this directory to your PATH system variable, which will make it possible for you to launch Play from anywhere.

Setting the PATH variable is OS-specific. Here are the instructions for OS X, Linux, and Windows:

  • Mac OS X— Open the file /etc/paths in a text editor, and add the path where you installed Play to the file.
  • Linux— Open your shell’s startup 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 it: PATH="$PATH":/path/to/play (with the proper path substituted).
  • Windows 7— Go to Control Panel > System and Security > System and click Advanced System Settings on the right side. Click the button Environment Variables. You’ll see a window listing variables (as in figure 1.2), and there should be a user variable called PATH. Simply add the path to your Play installation to the end of its value.
    Figure 1.2. The Windows Environment Variables dialog

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.

Now Play should be available from any new shell you open. Go ahead and try it out; open a shell, and enter the play command. You should get output similar to this:

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

play! 2.1.1 (using Java 1.7.0_21 and Scala 2.10.0),
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, this command didn’t do much yet. But Play does try to be helpful; it tells you why it couldn’t do anything (“This is not a play application!”), and it suggests a command you can use to get started (play new). This will be a recurring theme when using Play; whenever something goes wrong, Play will guess what you’re trying to do, explain exactly where things went wrong, and suggest a next step to fix it. This isn’t limited to the command-line output, though; we’ll see useful error messages like this in our browsers later on, too.

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

1.5.2. Creating your first application

A Play application is a directory on the filesystem that contains a certain structure that Play uses to find configuration information, code, and any other resources it needs. We don’t need to create this structure ourselves; Play will do it for us when we use the play new command. This command will turn the current directory into a Play application, or you can add the desired name of your new application as a parameter, and it’ll create that directory for you.

According to tradition, any first example in any sort of technical tutorial should be called “Hello World.” Go ahead and type the following command: play new HelloWorld. Play will ask you to confirm the name, so hit Enter when the question comes up.

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

play! 2.1.1 (using Java 1.7.0_21 and Scala 2.10.0)
http://www.playframework.org

The new application will be created in /Users/sietse/Hello World

What is the application name? [HelloWorld]
> HelloWorld

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

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

>

Play is now asking us what kind of project we want. Pick option 2, Java.

> 2

OK, application HelloWorld is created.

Have fun!

Congratulations, you’ve created your first Play 2 application. Let’s see what’s inside.

1.5.3. Play application structure

The play new command always 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. Don’t worry if you don’t know what all these terms mean yet; we’ll cover them in detail in chapter 2.

The full contents of a newly created application are shown next.

Listing 1.1. Files in a new Play application
├── README
├── app
│
   ├── controllers
│
   │   └── Application.java
│   └── views
│       ├── index.scala.html
│       └── main.scala.html
├── conf
│   ├── application.conf
│   └── routes
├── project
│   ├── build.properties
│   └── plugins.sbt
├── public
│   ├── images
│   │   └── favicon.png
│   ├── javascripts
│   │   └── jquery-1.9.0.min.js
│   └── stylesheets
│       └── main.css
├── build.sbt
└── test
    ├── ApplicationTest.java
    └── IntegrationTest.java

This directory structure is common to all Play applications.

Now that we’ve seen the files that make up our application, let’s see what it looks like. Time to run the application.

1.5.4. Running the application

Play 2 always needs to be started from within an application directory, so cd into it: cd HelloWorld. Now start Play simply by typing play.

~$ cd HelloWorld
~/HelloWorld$ play
[info] Loading global plugins from /Users/sietse/.sbt/plugins
[info] Loading project definition from /Users/sietse/HelloWorld/project
[info] Set current project to HelloWorld

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

play! 2.2.0 (using Java 1.7.0_21 and Scala 2.10.0),
http://www.playframework.org

> Type "help play" or "license" for more information.
> Type "exit" or use Ctrl+D to leave this console.

[Hello World] $

You’re now in Play’s console. In the console, you can run several commands to interact with your application. We’ll be introducing some of them in this chapter and others throughout the rest of the book, but you can always type play help to get a list of commands.

For now, we’ll stick to running the application. Type run.

[Hello World] $ run

[info] Updating {file:/Users/sietse/Hello%20World/}Hello World...
[info] Done updating.
--- (Running the application from SBT, auto-reloading is enabled) ---

[info] play - Listening for HTTP on port 9000...

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

Play has checked your application and its dependencies for updates, and started a web server that serves your application. Let’s see what it’s serving.

1.5.5. Accessing the running application

Now that the application is running, you can access a default welcome page at http://localhost:9000/. You should see the page shown in figure 1.3.

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

This is already a kind of “hello world”—an example of a running application that outputs something, so you can 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 we 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 is probably not something you’ll do every day.

Now 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. Let’s change the welcome message.

1.5.6. Changing the controller class

The file in your application that controls what result is sent in response to the request for http://localhost/ is app/controllers/Application.java. It’s a regular Java class, which currently contains one method, index. The method looks like this:

public static Result index() {
  return ok(index.render("Your new application is ready."));
}

The index method is called an action method. It contains the logic that determines the response to the current HTTP request. We’ll get into more detail about what this specific code means later, but for now it’s enough to understand that this is how Play renders the default welcome page.

Let’s change the output to something else. Simply edit the file app/controllers/ Application.java and replace the Application class’s index method with the following.

public static Result index() {
  return ok("Hello World!");
}

This defines an action method that generates an HTTP “OK” response with text content. If you still have the application running, you can save the file and reload http://localhost:9000/; it will serve a plain text document containing the customary greeting, as seen in figure 1.4.

Figure 1.4. Simple text output

As you can see, the output is a little boring. In this case, it’s more interesting if you make a mistake.

1.5.7. Add a compilation error

In the action method, remove the closing quote character from "Hello world", save the file, and reload the page in your web browser. You’ll get a helpful compilation error, as in figure 1.5.

Figure 1.5. 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.8. Use an HTTP request parameter

This is still not a proper web application example, though, because we didn’t use HTTP or HTML yet. Let’s make it a little more interactive and make it a proper HTML page. To start, add a new action method with a String parameter to the controller class:

public static Result hello(String name) {
  return ok("Hello " + name);
}

Now if you want to try to run this new method, you need to set up an HTTP path (say, /hello) that corresponds to this method. You’ll also want to link an HTTP query parameter called name to our method’s name parameter. This is called binding the parameter. To get this to work, we need to tell Play what we want to do.

The key to setting up this binding is in the file conf/routes. In fact, this file is the reason why the index method we saw before works in the first place. If you open up the file, you’ll see the following line:

GET /        controllers.Application.index()

That line is called a route, and it maps an HTTP path to an action method in our application. In this case, it maps the root URL (/) to Application.index().

In order to give our new hello() method a URL to reach it by, we’ll need to create a route for it. Add a new line to the conf/routes file to map the /hello to our new method, including the String parameter called name:

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

Now open http://localhost:9000/hello?name=Play! and you can see how the URL’s query string parameter is passed to the controller action. You should get output as in figure 1.6.

Figure 1.6. Output using an HTTP query parameter

An example web application that outputs only text isn’t very useful; we want HTML output. Let’s create an HTML template to go with our action method.

1.5.9. Add an HTML page template

Under the app/views directory, add a file named 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, a template with syntax based on the Scala programming language. Don’t worry, you don’t have to learn Scala! Think of it as any other new template language.

The first line of our template defines the parameter list—a name parameter in this case. The rest of the file is an HTML document layout of a simple page. If you take a closer look at the HTML body, you’ll see that it includes an HTML em tag whose content is an expression, @name. That will output the value of the name parameter.

In order to use this template, we have to edit the hello action method to return a result that wraps a call to the template instead of a String literal:

public static Result hello(String name) {
  return ok(views.html.hello.render(name));
}

Reload the web page—http://localhost:9000/hello?name=Play!—and you will see the formatted HTML output, like in figure 1.7.

Figure 1.7. Output using our HTML template

Congratulations, you’ve created your first Play application! You’ve seen all the major parts that make up a Play application. There’s one more thing to look at that’s not really part of a Play application, but still important while developing one; the Play console. Let’s see what exactly the console is for.

1.6. The console

Web developers are used to interacting with their applications through the browser. With Play, you can also use the console to interact with your web application’s development environment and build 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 Java source to hello/target/scala-2.9.1/classes...
[error] hello/app/controllers/Application.java:11:
          unclosed string literal
[error]     return ok(index.render("Hello world));
[error]                            ^
[error] hello/app/controllers/Application.java:11:
          ')' expected
[error]     return ok(index.render("Hello world));
[error]                                           ^
[error] hello/app/controllers/Application.java:12:
          ';' expected
[error]   }
[error]    ^
[error] hello/app/controllers/Application.java:14:
          reached end of file while parsing
[error] }
[error]  ^
[error] 4 errors
[error] {file:hello/}hello/compile:compile:
        javac returned nonzero exit code
[error] Total time: 0 s, completed Mar 19, 2012 11:29:53 AM
[hello] $

You can also start a Scala console, which gives you direct access to your compiled Play application:

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

scala>

As the name suggests, the Scala console uses Scala. This is because the build tool (sbt—Scala Build Tool) and the core framework are Scala-based. Like we said before, you don’t have to learn Scala to be able to use Play, but we did want to show you this useful feature of Play’s console. Certain things are easy enough to do, and are not particularly different from how you would do things in Java. One example of this is rendering a template, which is a Scala function that you can call like this:

scala> views.html.hello.render("Play!")
res1: 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 rendered a dynamic template in a web application that is not 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 without sacrificing enterprise features. Play 2 also introduces new goals expressed through the reactive-programming model. The result is a web framework that offers simplicity, productivity, and usability as well as structure and scalability. After starting with a first version implemented in Java, Play 2 introduces more type safety throughout the framework.

As soon as you start writing code, you go beyond Play’s background and its feature list to what really matters—the user experience that determines how much you’ll enjoy using Play. The good news is that Play achieves a level of simplicity, productivity, and usability that means that 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