Home > Articles > Programming > Java

Like this article? We recommend

Hello, Play!

No introductory technical article would be complete without the classic “Hello, World” example, so let’s go ahead and build a “Hello, Play” example.

Execute play new HelloPlay to create a new play application:

Stevens-MacBook-Pro:Workspace shaines$ play new HelloPlay
       _
 _ __ | | __ _ _  _
| '_ \| |/ _' | || |
|  __/|_|\____|\__ /
|_|            |__/

play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_25), http://www.playframework.com

The new application will be created in /Users/shaines/Documents/Workspace/HelloPlay

What is the application name? [HelloPlay]
> 

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

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

> 2
OK, application HelloPlay is created.

Have fun!

Stevens-MacBook-Pro:~ shaines$

When creating a new play application, you can choose to create a Java or a Scala application. Here we’ll stick to Java, but if you’re a Scala fan, you are free to create a Scala Play application as well.

The wizard creates the following artifacts for you:

README                README file to be included with your application
app                   Application sources
    controllers       Your application controllers (the C in MVC)
    views             Your application views (the V in MVC) – template files
    (models)          Your application model classes (the M in MVC)
    (assets)          Assets to be bundled with your application (typically need to be compiled)
        (stylesheets) CSS files (LESS files) for your application
        (javascripts) JavaScript/CoffeeScript files for your application
build.sbt             Main build file for your application
conf                  Configuration files
    application.conf  Main configuration file for your application
    routes            Routes file, which is used for mapping URIs to actions
project               SBT configuration files
    build.properties  Marker file for the SBT build tool
    plugins.sbt       SBT plug-in list
public                Public assets
    images            Application images
    stylesheets       Application CSS files
    javascripts       Application JavaScript files
test                 Source folder for unit tests

Play uses the Simple Build Tool (SBT) to build your application, so you’ll see a lot of “sbt” artifacts throughout the project. Your main application source code can be found under the “app” folder, which defines the following default directories:

  • controllers: Play uses the Model-View-Controller (MVC) design pattern, and this directory contains your controllers. Controllers define an action method that Play maps to a URI using the conf/routes file.
  • views: Views are implemented using a special template language called Scala templates. Don’t worry; you do not need to learn Scala. Scala templates are a lot like JSP files, but the markup in the files follow Scala constructs: Just think of these files as another templating language.
  •       models: Although this directory is not created for you by the wizard, it is where you will define your model classes. Note that Play applications tend to be domain-driven, so your model classes will have both data as well as persistence methods. This is a departure from Spring-like applications that define model objects as containing only data and persistence is delegated to a repository class, but if you follow the convention, then it will all make sense.
  • assets: Although this directory is not created for you, it is meant to contain your application assets and most typically assets that need to be compiled. You should store LESS files to be compiled to CSS files and CoffeeScript files to be compiled to JavaScript files in these directories. Assets that are already compiled, such as CSS and JavaScript files, and raw assets, such as images, should be stored in the “public” folder.

We’ll look at the other application resources as we need them. Let’s run our application and see what it does. Execute the “play” command from the “HelloScala” directory. You should output similar to the following:

Stevens-MacBook-Pro:HelloPlay shaines$ play
Getting org.scala-sbt sbt 0.13.0 ...
:: retrieving :: org.scala-sbt#boot-app
    confs: [default]
    43 artifacts copied, 0 already retrieved (12440kB/1006ms)
[info] Loading project definition from /Users/shaines/Documents/Workspace/HelloPlay/project
[info] Set current project to HelloPlay (in build file:/Users/shaines/Documents/Workspace/HelloPlay/)
       _
 _ __ | | __ _ _  _
| '_ \| |/ _' | || |
|  __/|_|\____|\__ /
|_|            |__/

play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_25), http://www.playframework.com

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

[HelloPlay] $

This leaves you in the Play console where you can manage your Play application. You can run the application by executing the run command:

[HelloPlay] $ run
[info] Updating {file:/Users/shaines/Documents/Workspace/HelloPlay/}helloplay...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.

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

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

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

Your Play application is now running and listening on port 9000. You can access it through the following URL:

http://localhost:9000

You should see a screen similar to Figure 1.

Figure 1 New Play Application Homepage

When you open http://localhost:9000, your browser executes an HTTP GET command for the “/” resource. Play’s conf/routes file maps the URI request for GET / to the action method defined in the controllers directory, Application class, index() method. Listing 1 shows the source code for the Application class.

Listing 1. Application.java

package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

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

The Application class is a controller because it extends Play’s play.mvc.Controller base class; you can browse the Play JavaDoc here. The Controller class defines a collection of helper methods, such as the ok() method (via its play.mvc.Results super class) that tells Play to return an HTTP 200 – OK response.

The index() method is referred to as an “action method” because HTTP requests are routed to “actions” for processing. All action methods are static and act as singletons – part of Play’s model is to ensure that all action methods are thread safe and should not manage state in the controller class.

There is a little Play magic going on in the index() method that I’d like to explore. When Play builds your application, it generates Scala source files from the view templates (app/views) to the following directory:

/target/scala-2.10/src_managed/main/views

And then it compiles those Scala source files to the following directory:

/target/scala-2.10/classes/views/html

Finally, this classes directory is added to your CLASSPATH so that when we import views.html.* we can access our compiled view templates. Putting this all together, a new Scala source file (target/scala-2.10/src_managed/main/views/html/index.template.scala) is created from the app/views/index.scala.html file, is compiled to a Java class (target/scala-2.10/classes/views/html/index.class), and that class is added to your CLASSPATH.

When you see index.render(“…”) it means that Play is executing the render() method, which accepts a String, on the index class. If Scala doesn’t scare you, take a look at the generated source file, find the render() method, and see what it’s doing:

/target/scala-2.10/src_managed/main/views/html/index.template.scala

The render() method returns a Scala object that implements the play.mvc.Content interface that contains the rendered HTML template. The rendered HTML is then passed to the ok() method, which wraps the HTML with an HTTP 200 response. Play then sends the final response back to the client.

Figure 2 shows a sequence diagram that summarizes this interaction.

Figure 2 Handling a Web Request Using a Scala Template

With that background out of the way, let’s update our Hello, Play application to return “Hello, Play” instead of showing the default application page. Modify the Application class’s index() method to what is shown in Listing 2.

Listing 2. Application.java (Updated for Hello, Play Message)

package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {
    public static Result index() {
        //return ok(index.render("Your new application is ready."));
        return ok( "Hello, Play!" );
    }
}

Now, instead of rendering a template, we simply return the text “Hello, Play!” wrapped in an HTTP 200 OK response. Save your file and go ahead and reload the page. (Note that you do not need to rebuild anything; Play will find the changed file and recompile the file for you.) Instead of seeing the rendered template, you should simply see the text “Hello, Play!”

Now let’s add a query parameter with the name of the person to greet. Listing 3 shows another version of the index() method that accepts a name String.

Listing 3. Application.java (Updated for Hello, your name Message)

package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {
    public static Result index( String name ) {
        //return ok(index.render("Your new application is ready."));
        return ok( "Hello, " + name + "!" );
    }
}

But for this to work, we need to update the routes file to tell Play that we expect a name parameter to be passed by the caller. Listing 4 shows our updated routes file.

Listing 4. conf/routes

# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
# GET     /                           controllers.Application.index()
GET     /                           controllers.Application.index(name:String)

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.at(path="/public", file)

The original routes file mapped an HTTP GET for the resource “/” to controllers.Application.index() but now we have augmented it to accept a name query parameter that is of type String. The syntax is different from Java: You specify the parameter name, followed by a colon and then the type of the parameter. In this example this is: “name:String”. Save the routes file and then reopen your browser to http://localhost:9000. You should see an error message stating that a name parameter is required and not provided! Now add a name parameter, as follows:

http://localhost:9000?name=YourName

Now you should see a response of “Hello, YourName”.

Before we close out this section, let’s build a simple Scala template HTML file and use it to render our Hello, Play text. First, let’s add a new action method to the Application class named hello(). Listing 5 shows the new contents of the Application.java file.

Listing 5. Application.java (New hello() method)

package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {
    public static Result index( String name ) {
        //return ok(index.render("Your new application is ready."));
        return ok( "Hello, " + name + "!" );
    }

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

The new hello() method invokes the views.html.hello class’s render method to generate HTML, which means we are going to have to create a new file in the apps/views folder named hello.scala.html. Listing 6 shows the contents of this Scala template.

Listing 6. hello.scala.html

@(name:String)
<!doctype html>
<html>
    <head>
        <title>Hello, Play</title>
    </head>
    <body>
        <h2>Hello, @name!</h2>
    </body>
</html>

The hello.scala.html template defines a required parameter at the beginning of the file:

@(name:String) 

The format is the same as defined in the routes file. This line requires a String parameter to be passed to the template’s render() method and then that value will be available through the name variable. Later in the template we obtain the value of the name variable by using the @name notation. We’ll review more details on Scala templates in the next article.

Finally we need to update the routes file, which is shown in Listing 7.

Listing 7. conf/routes (with New /hello URI)

# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
# GET     /                           controllers.Application.index()
GET     /                           controllers.Application.index(name:String)
GET     /hello                      controllers.Application.hello(name:String)

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.at(path="/public", file)

The new route maps GET /hello to the Application class’s hello() method. Save all three files and then load the new hello action with the following URL:

http://localhost:9000/hello?name=YourName

You should see the following output:

<!doctype html>
<html>
    <head>
        <title>Hello, Play</title>
    </head>
    <body>
        <h2>Hello, YourName!</h2>
    </body>
</html>

As you can see, the name parameter was substituted for YourName.

Summary

The Play Framework is not a traditional Java web framework and actually requires us to think about developing web applications differently. It runs in its own JVM, not inside a Servlet container, and it supports instant redeployment of applications without a build cycle. When building Play applications you are required to think in terms of HTTP and not in terms of Java.

This article presented an overview of Play, showed how to set up a Play environment, and then built a Hello, World application. In the next article we’ll look at building more complicated web applications, explore the Scala template language, and see how Play uses domain-driven objects. In the final article we’ll integrate Play with Akka to realize the true power of asynchronous messaging and see how to suspend a request while waiting for a response so that we can support more simultaneous requests than a traditional Java web application.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020