Home » Enterprise Java » Play! Framework Hello World Example

About Rambabu Posa

Rambabu Posa
Ram did his Masters in IS(Information Systems) from Andhra University, Vizag, India. He has 10+ years of experience in Java Ecosystem and 3+ years of experience in Scala Ecosystem. He is author of “Scala Reactive Programming” book. Apart from Java, Java EE and Scala, he is good at Spring, Hibernate, RESTful WebServices, NoSQL, BigData Hadoop Stack, Cloud, Groovy, Play Framework, Akka Toolkit, Lagom Framework, Kafka, Kubernetes, TDD, BDD,Agile and much more. He likes sharing his knowledge through writing tutorials and books.

Play! Framework Hello World Example

We are going to develop a series of Scala Web Applications or Microservices using Play Framework. This is our first post in this series.

In this post, we feature a comprehensive Play! Framework Hello World Example. We are going to develop our old style, to learn new concepts on “HelloWorld” example using Play Framework, Scala Language and SBT build tool. Both Play Framework and Scala are developed by Lightbend (formerly known as TypeSafe) Inc.

1. Introduction to Play Framework

Play Framework is a Light Weight, Stateless, Asynchronous, Highly Scalable, Non-Blocking and REST API based Modern Web applications development framework. Play 1.x was written in Java and Play 2.x was re-written completely in Scala. It supports both Java and Scala programming languages to develop Web applications.

1.1 Play Framework Features

Apart from basic web framework features, Play Framework supports the following most useful features:

  • Embedded Server (so no need a separate Web or Application server to deploy our applications)
  • Hot Reloading (to see our Changes in development environment quickly without restarting the server)
  • REST API (by design)
  • Reactive (by design)
  • Moduler
  • MVC Framework

1.2 Play Framework DI

Play Framework supports DI(Dependency Injection) very well. We can use any DI framework in our Play based applications like Google Guide, Java DI etc or we can use our own DI framework too.By default, Play Framework uses Guice Framework as its DI.

DI means resolving Bean’s or Component’s dependencies automatically. Play Framework supports the following two kinds of DI (Dependency Injection):

  • Compile-time DI
  • Run-time DI

In this post, we are going to develop the Play Framework Scala-based SBT project using Run-time DI using both Guide and Java DI.

The main advantages of DI are:

  • Avoid using Boilerplate code
  • Clear separation of Business Logic and Dependencies resolution so that our components can only concentrate on our business logic.

By going through this example, we will explore Play Framework major components and understand how Play DI (Dependency Injection) works with different DI frameworks.

2. Technologies used

In this post, we are going to use the following technologies:

  • Scala 2.12.6
  • Play Framework 2.6.13
  • SBT 1.1.5
  • IntelliJ IDEA

Before exploring the next steps, please try to install Java 1.8 or later version and the above mentioned software. Let us start developing our first Play Scala Web Application in the next section.

3. Play Scala Web Application

We are going to use IntelliJ IDE and SBT build tool to develop this application. If you are using IntelliJ IDE Ultimate Edition, first please create a Play Framework web application using IDE. If you are using IntelliJ IDE CE (Community Edition), please download the Play Scala Starter project from the following Lightbend’s Play Framework Examples GitHub location:

https://github.com/playframework/play-scala-starter-example

I have renamed this project as “PlayFrameworkScalaHelloWorldExample”, imported into IntelliJ IDE and deleted all files.

Then please continue the following steps to develop our HelloWorld application:

1. Add SBT Play Framework plugin to “plugins.sbt” file as shown below:

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.13")

Here we have mentioned SBT plugin of Play Framework, which will add all required dependencies to our project classpath automatically.

2. Add Scala version to “build.sbt” file and our project information as shown below:

name := "PlayFrameworkScalaHelloWorldExample"

version := "1.0.0"

lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.12.6"

libraryDependencies ++= Seq(guice)

Description:

  • We have defined our project name as “PlayFrameworkScalaHelloWorldExample”.
  • We are using Scala version as “2.12.6”.
  • We have define guice Library Dependencies as we are going to use Guide Injection (@Inject annotation in Controllers).

NOTE: Now onwards, we will refer “PlayFrameworkScalaHelloWorldExample” as PROJECT_ROOT

3. Add sbt version in “build.properties” file as shown below:

sbt.version=1.1.5

4. Create the following packages under PROJECT_ROOT/app folder:

  • com.jcg.examples.playscala.controllers: for define our Play Framework controllers.
  • com.jcg.examples.playscala.views: To define our Scala View Templates.

NOTE: Now onwards, we will refer “com.jcg.examples.playscala.controllers” as CONTROLLER_ROOT and “com.jcg.examples.playscala.views” as VIEWS_ROOT in the coming sections.

5. Define Scala View Template “helloworld.scala.html” under VIEWS_ROOT with the following content:

@(message: String)
<h1>Play Framework + Scala Example</h1>
<h2>@message</h2>

Description

  • By default, Play Framework using Twirl template engine. Its Scala based template engine.
  • It starts with arguments like @(message: String). That means it expects a String as an argument when we call it from Controllers.
  • In this template, we should use @{variable_name} to access any parameter or argument or variable name. For instance, @{message} or simply @message.

6. Define Play Framework controller “HelloWorldController” under CONTROLLER_ROOT with the following content:

package com.jcg.examples.playscala.controllers

import com.google.inject.Inject
import play.api.mvc.InjectedController

class HelloWorldController @Inject() extends InjectedController {

  def helloworld = Action {
    Ok(com.jcg.examples.playscala.views.html.helloworld("Dear JCG Readers, Welcome to Hello World!"))
  }

}

Description

    • To define Play Controllers, we need to mix-in either BaseController trait or one of it’s variants.
    • In Play Framework, BaseController defines required utility methods to generate Action and Results types. We can define a Play Controller using this component as shown below:
class HelloWorldController @Inject() (val controllerComponents: ControllerComponents) extends BaseController {
}
    • BaseController has two variants: AbstractController and InjectedController
    • AbstractController is an abstract class, has an abstract implementation of BaseController controller. We can define a Play Controller using this component as shown below:
class HelloWorldController @Inject() (val controllerComponents: ControllerComponents) extends AbstractController(controllerComponents) {
}
    • InjectedController is another variant of BaseController that gets its components using Method Injection (One kind of DI). We can define a Play Controller using this component as shown below:
class HelloWorldController @Inject() extends InjectedController {
}
    • Our controller should extend InjectedController trait.
    • We are using Guice DI (Dependency Injection) here: @Inject annotation.
    • We have defined our Controller Action: helloworld function.
    • We are making a call to helloworld view by passing a String as an argument.
    • In Play 2.3.x version or earlier, we were using Controller component to define our Play Controllers as shown below:
class HelloWorldController extends Controller {
}

However, this “Controller” is deprecated in Play 2.6.x version. It’s not recommended to use it in our applications.

Play Framework supports not only Guice DI, other DI frameworks too. For instance, we can use Java CDI annotations too as shown below:

package com.jcg.examples.playscala.controllers

import javax.inject.Inject
import play.api.mvc.InjectedController

class HelloWorldController @Inject() extends InjectedController {

  def helloworld = Action {
    Ok(com.jcg.examples.playscala.views.html.helloworld("Dear JCG Readers, Welcome to Hello World!"))
  }

}

7. Finally, we need to create Routes to map a Client Request to a Controller Action as shown below in “routes” file:

# HelloWorld Controller
GET     /helloworld     com.jcg.examples.playscala.controllers.HelloWorldController.helloworld

Description
We define Routings in “routes” file. Play Framework uses “routes” as default routing file. However, we can use any name (we will discuss how to use different routing filenames in my coming posts).

      • First, we mapped “GET” HTTP request method with “/helloworld” URI and HelloWorldController.helloworld function.
      • That means, when a client sends HTTP GET request using “/helloworld” URI like “GET /helloworld, it makes a call to our HelloWorldController” controller helloworld” function.

8. Our project structure looks like as shown in the below diagram:

Play Framework Hello World - Project Structure

Play Scala HelloWorld Project Structure

Description
If we observe the above diagram, Play Framework project structure is different from Java or Java EE project structure because it uses SBT build tool to manage it’s structure. It’s completely different from Maven project structure. Let us understand some important sections of this project structure below:

      • app: we should write all our source code under this directory like Controllers, Services, Repositories, Models etc.
      • conf: we should place all our project configurations under this directory like application.conf, message files for I18N etc.
      • project: we should configure SBT version and SBT plugins under this directory.
      • build.sbt: we should define project metadata like name, version and library dependencies.
      • test: we should write all our unit tests under this directory (we’ll use it in our future posts).
      • it: we should write all our IT (Integration Tests) under this directory (we’ll use it in our future posts).
      • logs: Play Embedded server automatically write logs under this directory. By default, Framework creates application.log file name under this directory.

NOTE: By default, Play Framework uses “Logback” logging framework to log details to “/logs/application.log” file. That’s why we have defined logback.xml file under “/conf” folder.

4. Test Application

In this section, we are going to up and running our Play + Scala HelloWorld example and try to test it using the following ways:

  • Test with Browser
  • Test with REST client

4.1 Up and Running application

To test our application we need to start our application using “sbt” command. SBT tool provides many commands to compile, build, run and test it.

First off all, cd to our PROJECT_ROOT folder:

cd /Users/ram/PlayScalaAkkaExamples/PlayFrameworkScalaHelloWorldExample

To compile application, we can use the following command

sbt compile
Play Framework Hello World - SBT compile command

SBT compile command

To run ourapplication, we can use the following command:

sbt run
Play Framework Hello World - SBT run command

SBT run command

NOTE: By défault, sbt run command starts Play Application at 9000 default port number so we can access our application using the following url:
http://localhost:9000/{RESTAPI-URI}

To run a Play Application at different port, we can use the following command:

sbt "run 9999"

This time, we can access our application using the following url:

Now our application is up and running, its time to test it in the coming sections.

4.2 Test with Browser

As Play Framework applications are REST API by design, we can test with any Web Browsers like IE, Chrome, Firfox etc., because they have REST Client internally.

Access our application using this url http://localhost:9000/helloworld as shown below:

Play Framework Hello World - HelloWorld With Web Browser

Access HelloWorld With Web Browser

4.3 Test with a REST Client

We can test Play Framework REST API using any REST Client. Here we are going to test our application using POSTMAN. Please download it from https://www.getpostman.com/ for free.

Access our application using this url http://localhost:9000/helloworld as shown below:

Play Framework Hello World - HelloWorld With POSTMAN

Access HelloWorld With POSTMAN

5. Conclusion

So, it is very easy to develop REST API using Play Framework. It is very powerful and modern framework to develop web applications using REST and Microservice architecture. It supports both Java and Scala programming languages.

By default, Play application support SBT build tool. In this post, we have implemented a very simple and minimal Play Framework web application. We will discuss and implement some more applications in my upcoming posts.

6. Download the Source Code

That was a Play! Framework Hello World Example & a Scala HelloWorld Web Application Tutorial.

Download
You can download the full source code of this example here: Play! Framework Hello World Example
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of