Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Hey Ninja🥷! Today we will be dealing with the Play framework of Java and Scala. We will be implementing hello world in this article to see how simple and efficient it is to use. Play is a web development framework of Java or Scala which has integrated various components and APIs for modern application development. So grab your coffee and bear with me while we implement hello world.
Initializing the project🤖
We can initialize our project on implementing hello world by the following steps.
Step 1: We must verify all the requirements for running Play before going through the tutorial.
Step 2: We obtain the appropriate zip file of the Play Java and Scala Starter Example project.
Step 3: We unzip and run the example following the steps in the README.md file.
When we run the tutorial application, it displays web pages with the same content and instructions contained here in the article. The tutorial includes a mistake. It has been made intentionally. Open the article and application pages in different tabs or browsers so that you may consult the article when you encounter the error. It will help you in fixing the error. So let us start by introducing Play Framework.
Introduction to Play Framework🎞️
Play is a full-stack framework. Some of its features are:
It may fulfil all our requirements to build a Web Application or REST service
an integrated HTTP server
better form handling
a powerful routing mechanism
Cross-Site Request Forgery (CSRF) protection
I18n support and many more
The Play combines many object-relational mapping (ORM) layers and supports Anorm, Ebean, Slick and JPA.
However, some customers use NoSQL and other ORMs or even access data from a REST service. We know that Play APIs are available in both Java and Scala languages.
The Play Framework uses Akka and Akka HTTP in its internal workings. This bestows Play applications with a stateless, non-blocking and event-driven architecture. These attributes provide horizontal and vertical scalability to Play and use resources more efficiently. Play projects contain Scala components. Play also includes a Java API. So, Java developers must not learn Scala to use Play efficiently.
Here are some of the characteristics which have compelled developers to fall in love with Play Framework:
Play's Model-View-Controller (MVC) architecture is familiar and easy to learn.
Direct support of everyday web development tasks and hot reloading saves precious time for the developers.
A sizeable active community promotes knowledge sharing.
Twirl templates render pages. The Twirl template language is:
Easy to learn
Requires no special editor
Provides type safety
It is compiled so that errors display in the browser.
Let us create a hello world page.
Creating the Hello World page🙋
Read the instructions and try implementing the Hello World page to this project.
We create a file named hello.scala.html in notepad(you can use any text editor of our choice and save it in this project's app/views directory. We add the following codes to the file:
We can understand the purpose of Twirl and HTML markup by looking at the following points:
The '@' sign asks the template engine to interpret what follows.
In our case, @main("Hello", assetsFinder) calls the main template, main.scala.html and passes it to the title of the page of "Hello" (we can ignore the assetsFinder argument here).
The content section contains the greeting "Hello World". The main template inserts this into the body of the page.
Now we can add an action method that will render the new page.
Adding an action method
We open the app/controllers/HomeController.java (or .scala) file to add an action method for the new page. Under the tutorial method (and before the closing brace), we add the following method:
<!--Java Code-->
public Result hello() {
return ok(views.html.hello.render(assetsFinder));
}
<!--Scala Code-->
def hello = Action {
Ok(views.html.hello())
}
We are supposed to add a route that maps the page to the new action method so that Play calls it whenever the browser requests the hello page. So let us see how we can define a route for implementing hello world.
Defining a route🌌
We open the conf/routes file to define a route for the new Hello page and add the following lines of code there :
GET /hello controllers.HomeController.hello
When we add a route to the routes file, Play's routes compiler automatically generates a router class that will call that action using an instance of our controller. The controller instances, by default, are created using dependency injection (refer to docs for Java and Scala).
We are now ready to test the new page. If we have stopped the application for some reason, we may restart it with the sbt run command.
We may enter the URL
http://localhost:9000/hello
and check the results of our work. The browser displays something like:
Customizing the greeting💁
Now that we have learnt to implement hello world, we will try to change the hello page to accept an HTTP request parameter. The steps include an intentional mistake to illustrate the feedback mechanism of Play.
So let us customize Hello World greeting.
We can alter the hello action method in the app/controllers/HomeController.java (or .scala) file so that it accepts a name parameter using the following code:
<!--Java Code-->
public result hello(String name) {
return ok(views.html.hello.render(assetsFinder));
}
<!--Scala Code-->
def hello(name: String) = Action {
Ok(views.html.hello())
}
In the conf/routes file, we can add a (name: String) parameter at the end of the hello using the code:
GET /hello controllers.HomeController.hello(name: String)
To avoid errors, we should declare all variables and their types in Twirl templates.
We insert a new line at the top of the app/views/hello.scala.html file
On that line, we add an @ directive which declares the name parameter and its type: @(name: String)
We change the text in the <h2> heading from Hello World! to <h2>Hello @name!</h2> so that we can use the variable on the page.
In the browser, we enter the following URL and enter any name as a query parameter to the hello method:
http://localhost:9000/hello?name=MyName.
The Play throws a compilation error that tells us that the render method in the return value needs a typed parameter.
To fix the compilation error, we alter the hello action method in HomeController so that it contains the name parameter when rendering the view:
public result hello(String name) {
return ok(views.html.hello.render(name, assetsFinder));
}
def hello(name: String) = Action {
Ok(views.html.hello(name))
}
Refresh the browser after saving the file. We will display a customized greeting similar to the following:
Frequently Asked Questions✍️
How to run the Play framework?
We have to download and install the Scala plugin for running Play framework applications. We can run our Play app by executing play run under the application root directory with the help of the command line.
Why do we use the Play framework?
With the help of the play framework, developing web applications with Java and Scala becomes very sophisticated. Play is created on a light, stateless and web-friendly architecture. Play provides minimal resource consumption.
Can we use the Play framework in Java?
Yes, we can use the Play framework with both Scala and Java. We have to install Java plugins. It is a very sophisticated and light framework that helps modern web development.
Conclusion
This post gave us a brief overview of Implementing Hello World using The Play framework. We learned various implementing techniques and best practices. I hope you enjoyed reading our blog on 'Implementing Hello World'.