Getting started with Play Framework
Ricardo Dev
Posted on December 15, 2020
Hi, in this post I want to show you how create a simple web application using Play Framework. It's very easy to use and configure, so the tools that we need to install in our computer are:
- sbt 1.4.1
- Java jdk8
- Scala 2.13.3
- Any IDE as IntelliJ, Eclipse o VSCode
Get the template
I'm going to use the template provide by Giter8, so in our terminal enter the next command:
$ sbt new playframework/play-scala-seed.g8
Then provide the project information.
This template generates a Play Scala project
name [play-scala-seed]:
organization [com.example]:
After execute the command we need to change to the folder where the project was created.
.
├── app
│ ├── controllers
│ │ └── HomeController.scala
│ └── views
│ ├── index.scala.html
│ └── main.scala.html
├── build.sbt
├── conf
│ ├── application.conf
│ ├── logback.xml
│ ├── messages
│ └── routes
├── project
│ ├── build.properties
│ └── plugins.sbt
├── public
│ ├── images
│ │ └── favicon.png
│ ├── javascripts
│ │ └── main.js
│ └── stylesheets
│ └── main.css
└── test
└── controllers
└── HomeControllerSpec.scala
The principal components are:
- app/controllers: Java clases to despatch the http requests.
- app/views: HTML templates uses for display information in a web page.
- conf: contain the routes to access the web resources in our project.
- public/images: static images.
- public/javascripts: scripts in Javascript used in application.
- public/stylesheets: files of stylesheet.
Next, open the proyect in your favorite IDE.
Run the project
Type the next command in the terminal at project root level and see the html web page in: http://localhost:9000
$ sbt run
Adding Actions
The Actions allows us define services to expose, so in the next snippet code I'll put a new method to make a simple currency conversion with location. In the HomeController add:
def conversionFrench(m: Float) = Action {
implicit request: Request[AnyContent] =>
val formated = String.format(Locale.FRANCE, "%10.2f",m)
Ok(views.html.index(formated))
}
Then we need to change the app/views/index.scala.html file and make the next changes:
@(value: String)
@main("Conversion currency: ") {
<h1>to french currency: @value</h1>
}
Create a route
The conf/routes defines the endpoint exposed for processing the request http from users, so I will change the route existed in this file.
GET /translate/:message controllers.HomeController.conversionFrench(message: Float)
Then check the browser.
http://localhost:9000/conversion/365
Done.
Conclusion
Is so easy implement new services and present in html just adding the correspond annotation and methods. If you looking for a solution that is lightweight and use Java or Scala you should try this.
GitHub repository
Posted on December 15, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.