Over a million developers have joined DZone.

Your First Application With Play and Scala

DZone's Guide to

Your First Application With Play and Scala

With the build tool sbt, you can use Scala to set up web applications. Let's see how you can use Scala and the Play framework together to make a simple app.

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

Today we are going to develop a simple play application using Scala.

To do so, we must have sbt installed in our system. Once installed, we issue the command

sbt new playframework/play-scala-seed.g8

Then we are presented with an interactive terminal in order to pass valuable information.

name [play-scala-seed]: PlayStarter
organization [com.example]: com.gkatzioura
scala_version [2.11.8]: 
scalatestplusplay_version [2.0.0]: 
play_version [2.5.13]: 

Then let's check what we have just created

cd playstarter
sbt run

Navigate to http://localhost:9000, and you'll see a basic Play, "Hello world."

By looking to our project structure, as expected, we have a directory with our controllers.
Consider our request being handled as an action. We issue a request and we receive an HTML view:

def index = Action { implicit request =>

As you can see, the HTML that is rendered is located in the views directory. Play comes with Twirl as a template engine.

At conf/routes, we can see how the route is configured to the index action. Let’s add a simple action to that controller that returns a text body.

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

We have to edit the routes file to specify the new route and the get parameter

GET     /greet                      controllers.HomeController.greet(name)

Then issue a request at http://localhost:9000/greet?john.

For the next step, we'll add a new route with a path parameter. Suppose we want to retrieve the total logins for a user. We'll implement an action that sends a fake number:

def loginCount(userId: String) = Action {

And then we register the route:

GET     /user/:userId/login/count          controllers.HomeController.loginCount(userId)

By issuing the request http://localhost:9000/user/18/login/count, we shall receive the number 14.

To sum up, we just implemented our first Play application. We also implemented some basic actions to our controller and passed some path and request parameters.

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

scala ,play ,app development ,java ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}