So, what is Play?

Exclusive offer: get 50% off this eBook here
Instant Play Framework Starter [Instant]

Instant Play Framework Starter [Instant] — Save 50%

Build your web applications from the ground up with the Play Framework for Java and Scala with this book and ebook

$12.99    $6.50
by Daniel Dietrich | June 2013 | Open Source Web Development

Play is a full-stack web framework created to make web application development on the JVM easier and more productive. It provides APIs for Java and Scala.

A full-stack web framework provides solutions for a wide range of time-consuming web development tasks. With Play, developers are focusing on implementing functionality instead of thinking about design and architecture, and re-inventing the wheel. Only a few lines are necessary to write a fully functional web application.

Traditional web frameworks running on the JVM tend to create an abstraction layer over another abstraction layer. These heavy-weight lasagne architectures introduce an additional technical boilerplate and configuration, distracting developers from reaching their goal. Play in turn reduces complexity and simplifies web development by aligning its architecture with the that of the web, instead of abstracting it away.

Users of the Play Framework are web developers. Developers care about code readability and maintainability, fast development cycles, and easy error recovery. Play was designed by web developers to meet these goals.

Play consists of well-known parts. The basic architecture of a Play application follows the model-view-controller pattern, having an HTTP interface at its heart. Cohesive controllers and composable views share the same model.

Code changes are made visible by a simple reload of the web page in the browser. Play takes care of compiling changes in the background, independent of the development environment. This makes the development turnaround fast and easy.

Play also takes care of errors. Developers don't have to read long JVM stack traces to locate an error. Instead, Play shows the significant information directly in the browser, leading the developer right to the origin of the error. It is a big advantage that Play is a JVM framework; almost all parts of a Play application are type-safe.

This is why it is fun to develop Play applications.

In this article by Daniel Dietrich author of Instant Play Framework Starter, we will see how easy it is to create new Play application

(For more resources related to this topic, see here.)

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.

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

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 I

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.

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.

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.

Summary

We saw 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 also looked at what we can do with the command-line interface of Play and how fast modifications of our application are made visible.

Finally, we looked at the setup of integrated development environments ( IDEs ).

Resources for Article :


Further resources on this subject:


Instant Play Framework Starter [Instant] Build your web applications from the ground up with the Play Framework for Java and Scala with this book and ebook
Published: May 2013
eBook Price: $12.99
See more
Select your format and quantity:

About the Author :


Daniel Dietrich

Daniel Dietrich is a Senior Software Engineer living in Kiel, Germany. He studied Computer Science with Mathematics as a subsidiary subject and earned his diploma degree at the Christian-Albrechts University of Kiel. He specializes in enterprise grade frontend and backend development with a current focus on building a financial risk services platform.

Daniel has been developing software for over 25 years, thereof, 15 years professionally. He started to program at the age of 11. His creative work was influenced by computer competitions during the 90s. In the late 90s, he began to develop web applications.

Daniel worked as a Software Developer for several companies and is currently employed at the HSH Nordbank. He is focused on designing enterprise architectures and implementing Java enterprise applications. He has a special interest in JVM languages and web frameworks, especially Scala and the Play Framework.

Books From Packt


Mastering TypoScript: TYPO3 Website, Template, and Extension Development
Mastering TypoScript: TYPO3 Website, Template, and Extension Development

 Akka Essentials
Akka Essentials

Ext JS 4 Web Application Development Cookbook
Ext JS 4 Web Application Development Cookbook

Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications
Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications

Instant Lift Web Applications How-to [Instant]
Instant Lift Web Applications How-to [Instant]

Learning Website Development with Django
Learning Website Development with Django

Play Framework Cookbook
Play Framework Cookbook

Learning Play! Framework 2
Learning Play! Framework 2


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software