What is Play?
Play is a high-productivity Java and Scala web application framework that integrates components and APIs for modern web application development. Play was developed by web developers for web application development.
Play uses Model-View-Controller (MVC) architecture so that It is familiar and easy to learn. Play is a full-stack framework so that Play includes all the components you need to build Web Applications and REST services, such as an integrated HTTP server, form handling, Cross-Site Request Forgery (CSRF) protection, a powerful routing mechanism, I18n support, and more.
Play’s lightweight, stateless, web-friendly architecture uses Akka and Akka Streams under the covers to provide predictable and minimal resource consumption (CPU, memory, threads).
Play is non-opinionated about database access, and integrates with many object relational mapping (ORM) layers. It supports Anorm, Slick, and JPA out of the box, but many customers use NoSQL or other ORMs.
Play Requirements
A Play application only needs to include the Play JAR files to run properly. These JAR files are published to the Maven Repository, therefore you can use any Java or Scala build tool to build a Play project. However, Play provides an enhanced development experience (support for routes, templates compilation and auto-reloading) when using the sbt.
Play requires:
- Java SE 1.8 or higher
- sbt - we recommend the latest version
To check that you have Java SE 1.8 or higher, enter the following in a terminal:
java -version
You should see something like:
openjdk version "1.8.0_222"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_222-b10)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.222-b10, mixed mode)
You can obtain Java SE from Oracle’s JDK Site.
If you want to use sbt to create a new project, you need to install the sbt launcher on your system. With sbt installed, you can use our giter8 template for Java or Scala to create your own project with a single command, using sbt new
. Find the links on the sbt download page to install the sbt launcher on your system and refer to the sbt documentation for details about how to set it up.
After install sbt launcher, we can use sbt command to create Play Java using sbt new command, for example:
sbt new playframework/play-java-seed.g8
After the template creates the project:
- Change into the top level project directory.
- Enter
sbt run
to download dependencies and start the system. - In a browser, enter http://localhost:9000 to view the welcome page.
The Play application layout
The layout of a Play application is standardized to keep things as simple as possible. After the first successful compilation, the project structure looks like this:
The app/
directory
The app
directory contains all executable artifacts: Java and Scala source code, templates and compiled assets’ sources.
There are three packages in the app
directory, one for each component of the MVC architectural pattern:
app/controllers
app/models
app/views
You can add your own packages, for example, an app/services
package.
More information is available on https://www.playframework.com/documentation/2.8.x/Anatomy url.
Using the sbt console
You can run single sbt commands directly. For example, to build and run Play, change to the directory of your project and run:
$ sbt run
To launch sbt in the interactive mode, change into the top-level of your project and enter sbt with no arguments:
$ cd my-first-app
my-first-app $ sbt
Tip: you can also launch some commands before getting into sbt shell by running shell at the end of task list. For example:
$ sbt clean compile shell
With sbt in the interactive mode, run the current application in development mode, use the run
command:
[my-first-app] $ run
You can also compile your application without running the HTTP server. The compile
command displays any application errors in the command window. For example, in the interactive mode, enter:
[my-first-app] $ compile
You can run tests without running the server. For example, in interactive mode, use the test
command:
[my-first-app] $ test
Type console
to enter the Scala console, which allows you to test your code interactively:
[my-first-app] $ console
Debug: You can ask Play to start a JPDA debug port when starting the console. You can then connect using Java debugger. Use the sbt -jvm-debug <port>
command to do that:
$ sbt -jvm-debug 9999
When a JPDA port is available, the JVM will log this line during boot:
Listening for transport dt_socket at address: 9999
You can use sbt features such as triggered execution.
For example, using ~ compile
:
[my-first-app] $ ~ compile
The compilation will be triggered each time you change a source file.
If you are using ~ run
:
[my-first-app] $ ~ run
The triggered compilation will be enabled while a development server is running.
You can also do the same for ~ test
, to continuously test your project each time you modify a source file:
[my-first-app] $ ~ test
You can also run commands directly without entering the Play console.
For example, enter sbt run
:
Use the help
command to get basic help about the
available commands. You can also use this with a specific command to get
information about that command:
[my-first-app] $ help run
Hello World example
Assume that we use of sbt
or gradlew
commands from a terminal, but you can also integrate Play projects with your favorite IDE.
Code of Hello World app is at https://github.com/playframework/play-samples/tree/2.8.x/play-java-hello-world-tutorial
When you enter http://localhost:9000/ in your browser:
- The browser requests the root
/
URI from the HTTP server using theGET
method. - The Play internal HTTP Server receives the request.
- Play resolves the request using the
routes
file, which maps URIs to controller action methods. - The action method renders the
index
page, using Twirl templates. - The HTTP server returns the response as an HTML page.
At a high level, the flow looks something like this:
Let’s look at the tutorial project to locate the implementation for:
- The routes file that maps the request to the controller method.
- The controller action method that defines how to handle a request to the root URI.
- The Twirl template that the action method calls to render the HTML markup.
index.scala.html
Twirl template file.
public Result index() {
return ok(views.html.index.render("Your new application is
return ok(javaguide.hello.html.index.render("Your new application is ready.", assetsFinder));
}
To view the route that maps the browser request to the controller method, open the conf/routes
file. A route consists of an HTTP method, a path, and an action. This
control over the URL schema makes it easy to design clean,
human-readable, bookmarkable URLs. The following line maps a GET request
for the root URL /
to the index
action in HomeController
:
GET / controllers.HomeController.index
Open app/views/index.scala.html
with your text editor. The main directive in this file calls the main template main.scala.html
with the string Welcome to generate the page. You can open app/views/main.scala.html
to see how a String
parameter sets the page title.
conf/routes file:
# Routes
# This file defines all application routes (Higher priority routes first)
# An example controller showing a sample home page
GET / controllers.HomeController.index
GET /explore controllers.HomeController.explore
GET /tutorial controllers.HomeController.tutorial
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
- Create the Hello World page
- Add an action method
- Define a route
- Customize the greeting
1. Create the Hello World page
Follow the instructions below to add a new Hello World page to this project.
With any text editor, create a file named hello.scala.html
and save it in the app/views
directory of this project. Add the following contents to the file:
@()(implicit assetsFinder: AssetsFinder)
@main("Hello") {
<section id="top">
<div class="wrapper">
<h1>Hello World</h1>
</div>
</section>
}
This Twirl and HTML markup accomplishes the following:
- The
@
sign tells the template engine to interpret what follows. - In this case,
@main("Hello", assetsFinder)
calls the main template,main.scala.html
and passes it the page title of"Hello"
(you can ignore theassetsFinder
argument for the time being). - The content section contains the
Hello World
greeting. The main template will insert this into the body of the page.
Now we are ready to add an action method that will render the new page.
2. Add an action method
To add an action method for the new page:
Open the app/controllers/HomeController.java
(or .scala
) file. Under the tutorial method and before the closing brace, add the following method:
- Java
-
public Result hello() { return ok(views.html.hello.render(assetsFinder)); }
- Scala
def hello = Action {
Ok(views.html.hello())
}
Note that, in HomeController.java, it needs to add following code pieces:
3. Define a route
To define a route for the new Hello page That maps the page to the method.:
Open the conf/routes
file and add the following line:
GET /hello controllers.HomeController.hello
When you add a route to the routes
file, Play’s routes compiler will automatically generate a router class
that calls that action using an instance of your controller. For more
information see the routing documentation. By default, the controller instances are created using dependency injection (see docs for Java and Scala).
You are now ready to test the new page. If you stopped the application for some reason, restart it with the sbt run
command.
Enter the URL http://localhost:9000/hello to view the results of your work. The browser should respond with something like the following:
4. Customize the greeting
As the final part of this tutorial, we’ll modify the hello page to accept an HTTP request parameter. The steps include a deliberate mistake to demonstrate how Play provides useful feedback.
To customize the Hello World greeting, follow the instructions below.
In the app/controllers/HomeController.java
(or .scala
) file, add the helloName
action method to accept a name parameter using the following code:
- Java
-
public Result helloName(String name) { return ok(views.html.hello.render(name, assetsFinder)); }
In the conf/routes
file, add a (name: String)
parameter at the end of the hello
:
GET /helloName controllers.HomeController.helloName(name: String)
In Twirl templates, all variables and their types must be declared. In the app/views/helloName.scala.html
file:
- Insert a new line at the top of the file.
- On that line, add an @ directive that declares the name parameter and its type:
@(name: String)
- To use the variable on the page, change the text in the
<h2>
heading fromHello World!
to<h2>Hello @name!</h2>
.
The end result will be:
@(name: String)(implicit assetsFinder: AssetsFinder)@main("Hello") {<section id="top"><div class="wrapper"><h2>Hello, @name</h2></div></section>}
In the browser, enter the following URL and pass in any name as a query parameter to the helloName method: http://localhost:9000/helloName?name=MyName, as the result It shows the following screen
Congrat! Our HelloWorld implementation by using Play framework is done. The first step to finding out Play framework has been completed.
0 comments:
Post a Comment