Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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 =>
    Ok(views.html.index())
}


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 {
    Ok(14)
}


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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
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 }}