2

INTRODUCTION OF PLAY FRAMEWORK USING SCALA

 2 years ago
source link: https://blog.knoldus.com/introduction-of-play-framework-using-scala/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Reading Time: 5 minutes

In this tutorial, we are going to take a look at the Introduction of Play Framework using Scala. We’ll learn the following things :

  • Setup for play framework
  • How to use development tools to develop new project
  • How to implement our own features

Additionally, we’ll examine its built-in testing capabilities.

1. Project Setup

To start with Introduction of Play Framework using Scala we should have sbt and at least java 8 install in our system.

Here, I am using IntelliJ IDEA 2021.3.2 (Community Edition) IDE, SBT 1.6.2 along with Java 8 to build our first project.

2. Project Creation

Open IntelliJ IDE and select scala project with sbt

Enter project name basicsOfPlay and select sbt, scala and java version as in the below snap:

It will take some time to setup Scala. Once the build is complete go to the terminal and execute below command.

sbt new playframework/play-scala-seed.g8

It load all the dependencies, once dependencies loaded then It will ask you to give project name, organization name like com.example, play framework version and Scala version. Enter all the details and execute.

In this example, I am entering the below details

Name : funwithplay

Organization : com.funwithplay

play_version : 2.8.13

scala_version : 2.13.8

Now we are ready to run our first project. Execute the below command in terminal and server will start.

cd funwithplay     //make sure you are in funwithplay directory. 
sbt run

The first time we run the project It may take some time, as it compiles and builds the libraries. Once it is started, we can open it with the URL  http://localhost:9000  in the browser and we will get the welcome page.

Congratulations!! We have created a HTTP server in the play framework and the good thing is that we have not touched any code yet.

3. Play framework project structure

In our project directory, we can see several directories created by the sbt  template but we are discussing mainly four which will use by us in the project: 

  • app/controllers : The controller directory – here we store our Scala code.
  • app/views : The views directory – here we save our HTML template.
  • conf : The config directory – It contains our router configuration which maps a request URL to a specific class and method.
  • public : The public directory – It contains static content.

Now we will start some changes into auto created files. Before moving to next we should know about the speciality of Play Framework like It provides “hit refresh workflow” means we will update our code into the ide and refresh the browser only to see the changes into browser without restarting the server.

4. Implementation

let’s create a new file in the app/view directory with the name readywithplay.scala.html and copy and paste the below code as it is.

@() @main("Welcome to Introduction to Play Framework!") { 

<h1>Ready to play with Play Framework.</h1>
<h2>Play is based on a lightweight, stateless, web-friendly architecture.</h2>
<h3>It Built on Akka</h3>
<h4>Play provides predictable and minimal resource consumption (CPU, memory, threads) for highly-scalable applications</h4>
}

As we add the HTML file so we have to update the scala code into controller directory.

Open the HomeController.scala file and change the line Ok(views.html.index()) to Ok(views.html.readywithplay())

let’s go to the browser and refresh it and now we can see our changes.

5. Addition of new Action

Now we are moving forward to define new action but before to define new action lets understand how play framework work internally. Once play server receives a request, It will go config/routes file and determine which controller and method will handle the request.The method defined inside a controller and used in the routes file is called an action.

We are going to define a new action in the HomeController class and config a new route. Our code will receive two string type parameters from the URL and print concatenation of the string in browser.

To implement a new action, we open the Scala file (HomeController.scala) and add a new method that accepts two parameters(str1 and str2), concat them and passes the result to the view template:

def stringConcatenation(str1: String, str2: String) = Action { 
implicit request: Request[AnyContent] =>
  val resultString = str1 + " " + str2
  Ok(views.html.index(resultString))
}

Now, let’s open the  index.scala.html file, add the resultString parameter on top of the file, and use it in the content:

@(resultString: String)

@main("Concatenation of two string") {
<h1>Concatenation of two string is  @resultString </h1>
} 

We just defined a function stringConcatenationthat generates a page. The first line of the view file describes the function parameters. The other lines are the code that generates the output.

The concatenation is calculated in the controller and passed to the Ok function which returns the content with the status code 200 OK.

Now, we’ll need to open the routes file to add the new path and action:

GET  /resultString/:str1/:str2  controllers.HomeController.stringConcatenation(str1: String, str2: String)

The route consists of three parts. First, we specify the HTTP method. Next, we define the path and its variables. Finally, we’re specifying the controller and which action should be used to handle the request. Note that here we use the path variables as the parameters of the function.

In the browser, when we open the following URL : http://localhost:9000/resultString/Hello/Play , we should see this page:

6. Testing of above implementation

Sbt provides build-in testing capabilities. Inside tests/controllers directory we will find HomeControllerSpec file to write the test case.

We should write the test case for additional route that we have created. We define a new test case and use assertion to verify the result. Copy the below test case into HomeControllerSpec file.

"render a page that prints the concatenation of two strings" in { 

val request = FakeRequest(GET, "/resultString/Play/Framework") 
val stringconcatenation = route(app, request).get 

status(stringconcatenation) mustBe OK 
contentType(stringconcatenation) mustBe Some("text/html") 
contentAsString(sumOfNumbers) must include ("Concatenation of two string is Play Framework")
}

To execute the test cases we use below command

sbt test

7. Conclusion

In this tutorial(Introduction of Play Framework using Scala), We learnt about setup of play framework and create a simple web page with the help of scala. We modify controller class and add a new route in config directory.

8. References

https://www.playframework.com/documentation

Scala Future

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK