Scala

Your first Web application with Play and Scala

Today we are going to develop a simple play application using Scala. To do so we must have sbt installed to 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 us check what we have just created

cd playstarter
sbt run

Navigate to http://localhost:9000 and you have 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 we the html that is rendered is located at 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

On the next step we shall add a new route with a path param

Suppose we want to retrieve the total logins for a user. We implement an action that send 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 achieved to pass some path and request parameters.

Reference: Your first Web application with Play and Scala from our JCG partner Emmanouil Gkatziouras at the gkatzioura blog.

Emmanouil Gkatziouras

He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button