SlideShare ist ein Scribd-Unternehmen logo
1 von 75
Knoldus Software LLP
Knoldus Software LLP
New Delhi , India
www.knoldus.com
Neelkanth Sachdeva
@NeelSachdeva
neelkanthsachdeva.wordpress.com
Kick start to
Knoldus Software LLP
I am
Software Consultant
@ Knoldus Software LLP , New Delhi
( The only Typesafe partner in Asia )
http://www.knoldus.com/
Co-Founder
@ My Cell Was Stolen
http://www.mycellwasstolen.com/
Knoldus Software LLP
Introduction to
Knoldus Software LLP
Agenda
Introduction
● Overview
● Features of Play
● Components of Play
● Action , Controller ,
Result
● Routes
● The template engine
● HTTP Form
Other concepts
● Web Services
● Working with XML
● Working with JSON
Development
● Developing a application
using Play
Deployment
● Deploying the Play
application to Heroku
Knoldus Software LLP
Overview
Play framework is :
➢ Created by Guillaume Bort, while working at Zenexity.
➢ An open source web application framework.
➢ Lightweight, stateless, web-friendly architecture.
➢ Written in Scala and Java.
➢ Support for the Scala programming language has been
available since version 1.1 of the framework.
Knoldus Software LLP
Features of Play!
➢ Stateless architecture
➢ Less configuration: Download, unpack and
develop.
➢ Faster Testing
➢ More elegant API
➢ Modular architecture
➢ Asynchronous I/O
Knoldus Software LLP
Stateless Architecture-The base of Play
Each request as an independent transaction
that is unrelated to any previous request so that
the communication consists of independent
pairs of requests and responses.
Knoldus Software LLP
Basic Play ! components
➢ JBoss Netty for the web server.
➢ Scala for the template engine.
➢ Built in hot-reloading
➢ sbt for dependency management
Knoldus Software LLP
Action, Controller & Result
Action :-
Most of the requests received by a Play application are
handled by an Action.
A play.api.mvc.Action is basically a
(play.api.mvc.Request => play.api.mvc.Result)
function that handles a request and generates a
result to be sent to the client.
val hello = Action { implicit request =>
Ok("Request Data [" + request + "]")
}
Knoldus Software LLP
● Controllers :-
Controllers are action generators.
A singleton object that generates Action values.
The simplest use case for defining an action
generator is a method with no parameters that
returns an Action value :
import play.api.mvc._
object Application extends Controller {
def index = Action {
Ok("Controller Example")
}
}
Knoldus Software LLP
val ok = Ok("Hello world!")
val notFound = NotFound
val pageNotFound = NotFound(<h1>Page not found</h1>)
val badRequest =
BadRequest(views.html.form(formWithErrors))
val oops = InternalServerError("Oops")
val anyStatus = Status(488)("Strange response type")
Redirect(“/url”)
Results
Knoldus Software LLP
Knoldus Software LLP
package controllers
import play.api._
import play.api.mvc._
object Application extends Controller {
def index = Action {
//Do something
Ok
}
}
Controller ( Action Generator )
index Action
Result
Knoldus Software LLP
HTTP routing :
An HTTP request is treated as an event by the
MVC framework. This event contains two
major pieces of information:
● The request path (such as /local/employees ),
including the query string.
● The HTTP methods (GET, POST, …).
Routes
Knoldus Software LLP
The conf/routes file
# Home page
GET / controllers.Application.index
GET - Request Type ( GET , POST , ... ).
/ - URL pattern.
Application - The controller object.
Index - Method (Action) which is being called.
Knoldus Software LLP
The template engine
➢ Based on Scala
➢ Compact, expressive, and fluid
➢ Easy to learn
➢ Play Scala template is a simple text file, that contains
small blocks of Scala code. They can generate any text-
based format, such as HTML, XML or CSV.
➢ Compiled as standard Scala functions.
Knoldus Software LLP
● Because Templates are compiled, so you will see any
errors right in your browser
@main
● views/main.scala.html template act as a
main layout template. e.g This is our
Main template.
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
</head>
<body>
<section class="content">@content</section>
</body>
</html>
● As you can see, this template takes two
parameters: a title and an HTML content block.
Now we can use it from any other template e.g
views/Application/index.scala.html template:
@main(title = "Home") {
<h1>Home page</h1>
}
Note: We sometimes use named parameters(like @main(title =
"Home"), sometimes not like@main("Home"). It is as you want,
choose whatever is clearer in a specific context.
Syntax : the magic ‘@’ character
Every time this character is encountered, it indicates the
begining of a Scala statement.
@employee.name // Scala statement starts here
Template parameters
A template is simply a function, so it needs parameters,
which must be declared on the first line of the template
file.
@(employees: List[Employee], employeeForm: Form[String])
Iterating : You can use the for keyword in order
to iterate.
<ul>
@for(c <- customers) {
<li>@c.getName() ($@c.getCity())</li>
}
</ul>
If-blocks : Simply use Scala’s standard if
statement:
@if(customers.isEmpty()) {
<h1>Nothing to display</h1>
} else {
<h1>@customers.size() customers!</h1>
}
Compile time checking by Play
- HTTP routes file
- Templates
- Javascript files
- Coffeescript files
- LESS style sheets
HTTP Form
The play.api.data package contains several
helpers to handle HTTP form data submission
and validation. The easiest way to handle a form
submission is to define a play.api.data.Form
structure:
Lets understand it by a defining simple form
object FormExampleController extends Controller {
val loginForm = Form(
tuple(
"email" -> nonEmptyText,
"password" -> nonEmptyText))
}
This form can generate a (String, String) result
value from Map[String, String] data:
The corresponding template
@(loginForm :Form[(String, String)],message:String)
@import helper._
@main(message){
@helper.form(action = routes.FormExampleController.authenticateUser) {
<fieldset>
<legend>@message</legend>
@inputText(
loginForm("email"), '_label -> "Email ",
'_help -> "Enter a valid email address."
)
@inputPassword(
loginForm("password"),
'_label -> "Password",
'_help -> "A password must be at least 6 characters."
)
</fieldset>
<input type="submit" value="Log in ">
}
}
Putting the validation
● We can apply the validation at the time of
defining the form controls like :
val loginForm = Form(
tuple(
"email" -> email,
"password" -> nonEmptyText(minLength = 6)))
●
email means : The textbox would accept an valid Email.
●
nonEmptyText(minLength = 6) means : The textbox would accept atleast 6
characters
Constructing complex objects
You can use complex form mapping as well.
Here is the simple example :
case class User(name: String, age: Int)
val userForm = Form(
mapping(
"name" -> text,
"age" -> number)(User.apply)(User.unapply))
Calling WebServices
● Sometimes there becomes a need to call other
HTTP services from within a Play application.
● This is supported in Play via play.api.libs.ws.WS
library, which provides a way to make asynchronous
HTTP calls.
● It returns a Promise[play.api.libs.ws.Response].
Making an HTTP call
● GET request :
val returnedValue : Promise[ws.Response] = WS.url("http://mysite.com").get()
● POST request :
WS.url("http://mysite.com").post(Map("key" -> Seq("value")))
Example
● Lets make a WS GET request on
ScalaJobz.com API.
● Result :
This call would return the JSON of jobs from
scalajobz.com.
● Route definition:
GET /jobs controllers.Application.jobs
● Controller :
/**
* Calling web services
*/
def jobs = Action {
WS.url("http://www.scalajobz.com/getAllJobs").get().map
{
response => println(response.json)
}
Ok("Jobs Fetched")
}
Working with XML
●
An XML request is an HTTP request using a valid.An XML request is an HTTP request using a valid.
XML payload as the request body.XML payload as the request body.
●
It must specify theIt must specify the text/xmltext/xml MIME type in itsMIME type in its
Content-TypeContent-Type header.header.
●
By default anBy default an ActionAction uses a any content bodyuses a any content body
parser, which lets you retrieve the body as XMLparser, which lets you retrieve the body as XML
(as a NodeSeq)(as a NodeSeq)
Defining The Route :
POST /sayHello controllers.Application.sayHello
Defining The Controller :
package controllers
import play.api.mvc.Action
import play.api.mvc.Controller
object Application extends Controller {
def sayHello = Action { request =>
request.body.asXml.map { xml =>
(xml  "name" headOption).map(_.text).map { name =>
Ok("Hello " + name + " ")
}.getOrElse {
BadRequest("Missing parameter [name]")
}
}.getOrElse {
BadRequest("Expecting Xml data")
}
}
}
Let us make a POST request containing XML data
Working with JSON
1. A JSON request is an HTTP request using a valid JSON1. A JSON request is an HTTP request using a valid JSON
payload as request body.payload as request body.
2. It must specify the text/json or application/json mime type2. It must specify the text/json or application/json mime type
in its Content-Type header.in its Content-Type header.
3. By default an Action uses an any content body parser,3. By default an Action uses an any content body parser,
which lets you retrieve the body as JSON.which lets you retrieve the body as JSON.
(as a JsValue).(as a JsValue).
Defining The Route :
POST /greet controllers.Application.greet
Defining The Controller :
package controllers
import play.api.mvc.Controller
import play.api.mvc.Action
object Application extends Controller {
def greet = Action { request =>
request.body.asJson.map { json =>
(json  "name").asOpt[String].map { name =>
Ok("Hello " + name + " ")
}.getOrElse {
BadRequest("Missing parameter [name]")
}
}.getOrElse {
BadRequest("Expecting Json data")
}
}
}
Lets make a POST request containing JSON data
Knoldus Software LLP
Lets then
Knoldus Software LLP
Prerequisites
1. Download the Scala SDK from here.
http://scala-ide.org/download/sdk.html
2. A basic knowledge of the Eclipse user interface
Knoldus Software LLP
Setting up Play 2.1
1. Download Play framework 2.1.3 from
http://www.playframework.org.
2. Unzip it in your preferred location. Let's say
/path/to/play for the purpose of this document.
3. Add the Play folder to your system PATH
export PATH=$PATH:/path/to/play
Knoldus Software LLP
Creating a Play 2.1.3 application
In your development folder, ask Play to create
a new web application, as a simple Scala
application.
Knoldus Software LLP
Creating a new project
Knoldus Software LLP
● Clone MyOffice app from here as
git clone git@github.com:knoldus/ScalaTraits-August2013-Play.git
Knoldus Software LLP
Importing the project in to eclipse IDE
Knoldus Software LLP
Running the project
Knoldus Software LLP
The Project Structure
Knoldus Software LLP
The project “MyOffice” mainly contains :
● app / : Contains the application’s core, split
between models, controllers and views
directories.
● Conf / : Contains the configuration files.
Especially the main application.conf file,the
routes definition files. routes defines the
routes of the UI calls.
Knoldus Software LLP
● project :: Contains the build scripts.
● public / :: Contains all the publicly available
resources, which includes JavaScript,
stylesheets and images directories.
● test / :: Contains all the application tests.
Knoldus Software LLP
Edit the conf/routes file:
# Home page
GET / controllers.Application.index
# MyOffice
GET /employees controllers.MyOfficeController.employees
POST /newEmployee controllers.MyOfficeController.newEmployee
POST /employee/:id/deleteEmployee
controllers.MyOfficeController.deleteEmployee(id: Long)
Knoldus Software LLP
Add the MyOfficeController.scala object under controllers
& define the methods those will perform the action.
package controllers
import play.api.mvc._
object MyOfficeController extends Controller {
/**
* Total Employees In Office
*/
def employees = TODO
/**
* Add A New Employee
*/
def newEmployee = TODO
/**
* Remove An Employee
*/
def deleteEmployee(id: Long) = TODO
}
Knoldus Software LLP
● As you see we use TODO to define our action
implementations. Because we haven't write the action
implementations yet, we can use the built-in TODO action
that will return a 501 Not Implemented HTTP response.
Now lets hit the http://localhost:9000/employees & see what
we find.
Knoldus Software LLP
● Lets define the models in our MyOffice
application that will perform the business logic.
Preparing the Employee model
Before continuing the implementation we need to define how the
Employee looks like in our application.
Create a case class for it in the app/models/Employee.scala file.e.
case class Employee(id: Long, name : String)
Each Employee is having an :
● Id - That uniquely identifies the Employee
● name - Name of the Employee
Knoldus Software LLP
The Employee model
package models
case class Employee(id: Long, name: String)
object Employee {
/**
* All Employees In Office
*/
def allEmployees(): List[Employee] = Nil
/**
* Adding A New Employee
*/
def newEmployee(nameOfEmployee: String) {}
/**
* Delete Employee
* @param id : id Of The Employee To Be Deleted
*/
def delete(id: Long) {}
}
Knoldus Software LLP
Now we have our :
- Controller MyOfficeController.scala
- Model Employee.scala
Lets write Application template employee.scala.html.
The employee form :
Form object encapsulates an HTML form definition, including
validation constraints. Let’s create a very simple form in the
Application controller: we only need a form with a single
name field. The form will also check that the name provided
by the user is not empty.
Knoldus Software LLP
The employee form in MyOfficeController.scala
val employeeForm = Form(
"name" -> nonEmptyText)
The employee form in MyOfficeController.scalaThe employee form in MyOfficeController.scala
The type of employeeForm is the Form[String] since it
is a form generating a simple String. You also need to
Import some play.api.data classes.
Knoldus Software LLP
@(employees: List[Employee], employeeForm: Form[String])
@import helper._
@main("My Office") {
<h1>Presently @employees.size employee(s)</h1>
<ul>
@employees.map { employee =>
<li>
@employee.name
@form(routes.MyOfficeController.deleteEmployee(employee.id)) {
<input type="submit" value="Remove Employee">
}
</li>
}
</ul>
<h2>Add a new Employee</h2>
@form(routes.MyOfficeController.newEmployee) {
@inputText(employeeForm("name"))
<input type="submit" value="Add Employee">
}
}
Knoldus Software LLP
Rendering the employees.scala.html page
Assign the work to the controller method
employees.
/**
* Total Employees In Office
*/
def employees = Action {
Ok(views.html.employee(Employee.allEmployees(), employeeForm))
}
● Now hit the http://localhost:9000/employees and
see what happens.
Knoldus Software LLP
Knoldus Software LLP
Form Submission
●
For now, if we submit the employee creation form, we still get theFor now, if we submit the employee creation form, we still get the
TODO page. Let’s write the implementation of theTODO page. Let’s write the implementation of the newEmployeenewEmployee
action :action :
def newEmployee = Action { implicit request =>
employeeForm.bindFromRequest.fold(
errors =>
BadRequest(views.html.employee(Employee.allEmployees(),
employeeForm)),
name => {
Employee.newEmployee(name)
Redirect(routes.MyOfficeController.employees)
})
}
Knoldus Software LLP
Persist the employees in a database
● It’s now time to persist the employees in a database to
make the application useful. Let’s start by enabling a
database in our application. In the conf/application.conf
file, add:
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
For now we will use a simple in memory database using H2.
No need to restart the server, refreshing the browser is
enough to set up the database.
Knoldus Software LLP
● We will use Anorm in this tutorial to query the database.
First we need to define the database schema. Let’s use Play
evolutions for that, so create a first evolution script in
conf/evolutions/default/1.sql:
# Employees schema
# --- !Ups
CREATE SEQUENCE employee_id_seq;
CREATE TABLE employee (
id integer NOT NULL DEFAULT nextval('employee_id_seq'),
name varchar(255)
);
# --- !Downs
DROP TABLE employee;
DROP SEQUENCE employee_id_seq;
Knoldus Software LLP
Now if you refresh your browser, Play will warn you that your
database needs evolution:
Knoldus Software LLP
● It’s now time to implement the SQL queries in the Employee companion
object, starting with the allEmployees() operation. Using Anorm we can
define a parser that will transform a JDBC ResultSet row to a Employee value:
import anorm._
import anorm.SqlParser._
val employee = {
get[Long]("id") ~
get[String]("name") map {
case id ~ name => Employee(id, name)
}
}
Here, employee is a parser that, given a JDBC ResultSet rowHere, employee is a parser that, given a JDBC ResultSet row
with at least an id and a name column, is able to create awith at least an id and a name column, is able to create a
Employee value.Employee value.
Knoldus Software LLP
Let us write the implementation of our methods in Employee model.
/**
* Add A New Employee
*/
def newEmployee = Action { implicit request =>
employeeForm.bindFromRequest.fold(
errors =>
BadRequest(views.html.employee(Employee.allEmployees(),
employeeForm)),
name => {
Employee.newEmployee(name)
Redirect(routes.MyOfficeController.employees)
})
}
/**
* Remove An Employee
*/
def deleteEmployee(id: Long) = Action {
Employee.delete(id)
Redirect(routes.MyOfficeController.employees)
}
Knoldus Software LLP
The model methods
/**
* All Employees In Office
*/
def allEmployees(): List[Employee] = DB.withConnection { implicit c =>
SQL("select * from employee").as(employee *)
}
/**
* Adding A New Employee
*/
def newEmployee(nameOfEmployee: String) {
DB.withConnection { implicit c =>
SQL("insert into employee (name) values ({name})").on(
'name -> nameOfEmployee).executeUpdate()
}
}
/**
* Delete Employee
* @param id : id Of The Employee To Be Deleted
*/
def delete(id: Long) {
DB.withConnection { implicit c =>
SQL("delete from employee where id = {id}").on(
'id -> id).executeUpdate()
}
}
Knoldus Software LLP
That's it
Knoldus Software LLP
Let us use the Application “MyOffice”
Knoldus Software LLP
Lets deploy the
App to
Knoldus Software LLP
Heroku needs a file named ‘Procfile‘ for each
application to be deployed on it.
What is Procfile ?
Procfile is a mechanism for declaring what
commands are run when your web or worker
dynos are run on the Heroku platform.
Knoldus Software LLP
Procfile content :
web: target/start -Dhttp.port=$PORT -DapplyEvolutions.default=true
Knoldus Software LLP
Lets Deploy our application
1. Create a file Procfile and put it in the root of
your project directory.
2. Initiate the git session for your project and
add files to git as
git init
git add .
Knoldus Software LLP
3. Commit the changes for the project to git as
git commit -m init
4. On the command line create a new application
using the “cedar” stack:
heroku create -s cedar
5. Add the git remote :
git remote add heroku //TheCloneUrlOnTheHerokuApp//
Knoldus Software LLP
6. Application is ready to be deployed to the cloud. push
the project files to heroku as:
git push heroku master
Go to your heroku account -> MyApps and you’ll
find a new application that you had just created.
Launch the URL and have a look to your running
application on heroku. You can also rename your
application.
Knoldus Software LLP

Weitere ähnliche Inhalte

Was ist angesagt?

SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLJerry Yang
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEHitesh Mohapatra
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Sven Efftinge
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
#Pharo Days 2016 Reflectivity
#Pharo Days 2016 Reflectivity#Pharo Days 2016 Reflectivity
#Pharo Days 2016 ReflectivityPhilippe Back
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
 

Was ist angesagt? (18)

Xml parsers
Xml parsersXml parsers
Xml parsers
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQL
 
5 xml parsing
5   xml parsing5   xml parsing
5 xml parsing
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Knolx session
Knolx sessionKnolx session
Knolx session
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]
 
Corba by Example
Corba by ExampleCorba by Example
Corba by Example
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
#Pharo Days 2016 Reflectivity
#Pharo Days 2016 Reflectivity#Pharo Days 2016 Reflectivity
#Pharo Days 2016 Reflectivity
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 

Ähnlich wie Create a basic Play application

Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)Ajay Khatri
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsAdrien Guéret
 
Angular Presentation
Angular PresentationAngular Presentation
Angular PresentationAdam Moore
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play FrameworkKnoldus Inc.
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1Paras Mendiratta
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JSAkshay Mathur
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 
Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4DEVCON
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed versionBruce McPherson
 

Ähnlich wie Create a basic Play application (20)

Play 2.0
Play 2.0Play 2.0
Play 2.0
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
Alteryx SDK
Alteryx SDKAlteryx SDK
Alteryx SDK
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
 

Mehr von Knoldus Inc.

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxKnoldus Inc.
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance TestingKnoldus Inc.
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxKnoldus Inc.
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationKnoldus Inc.
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 

Mehr von Knoldus Inc. (20)

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptx
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance Testing
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptx
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower Presentation
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 

Kürzlich hochgeladen

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 

Create a basic Play application

  • 1. Knoldus Software LLP Knoldus Software LLP New Delhi , India www.knoldus.com Neelkanth Sachdeva @NeelSachdeva neelkanthsachdeva.wordpress.com Kick start to
  • 2. Knoldus Software LLP I am Software Consultant @ Knoldus Software LLP , New Delhi ( The only Typesafe partner in Asia ) http://www.knoldus.com/ Co-Founder @ My Cell Was Stolen http://www.mycellwasstolen.com/
  • 4. Knoldus Software LLP Agenda Introduction ● Overview ● Features of Play ● Components of Play ● Action , Controller , Result ● Routes ● The template engine ● HTTP Form Other concepts ● Web Services ● Working with XML ● Working with JSON Development ● Developing a application using Play Deployment ● Deploying the Play application to Heroku
  • 5. Knoldus Software LLP Overview Play framework is : ➢ Created by Guillaume Bort, while working at Zenexity. ➢ An open source web application framework. ➢ Lightweight, stateless, web-friendly architecture. ➢ Written in Scala and Java. ➢ Support for the Scala programming language has been available since version 1.1 of the framework.
  • 6. Knoldus Software LLP Features of Play! ➢ Stateless architecture ➢ Less configuration: Download, unpack and develop. ➢ Faster Testing ➢ More elegant API ➢ Modular architecture ➢ Asynchronous I/O
  • 7. Knoldus Software LLP Stateless Architecture-The base of Play Each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of requests and responses.
  • 8. Knoldus Software LLP Basic Play ! components ➢ JBoss Netty for the web server. ➢ Scala for the template engine. ➢ Built in hot-reloading ➢ sbt for dependency management
  • 9. Knoldus Software LLP Action, Controller & Result Action :- Most of the requests received by a Play application are handled by an Action. A play.api.mvc.Action is basically a (play.api.mvc.Request => play.api.mvc.Result) function that handles a request and generates a result to be sent to the client. val hello = Action { implicit request => Ok("Request Data [" + request + "]") }
  • 10. Knoldus Software LLP ● Controllers :- Controllers are action generators. A singleton object that generates Action values. The simplest use case for defining an action generator is a method with no parameters that returns an Action value : import play.api.mvc._ object Application extends Controller { def index = Action { Ok("Controller Example") } }
  • 11. Knoldus Software LLP val ok = Ok("Hello world!") val notFound = NotFound val pageNotFound = NotFound(<h1>Page not found</h1>) val badRequest = BadRequest(views.html.form(formWithErrors)) val oops = InternalServerError("Oops") val anyStatus = Status(488)("Strange response type") Redirect(“/url”) Results
  • 13. Knoldus Software LLP package controllers import play.api._ import play.api.mvc._ object Application extends Controller { def index = Action { //Do something Ok } } Controller ( Action Generator ) index Action Result
  • 14. Knoldus Software LLP HTTP routing : An HTTP request is treated as an event by the MVC framework. This event contains two major pieces of information: ● The request path (such as /local/employees ), including the query string. ● The HTTP methods (GET, POST, …). Routes
  • 15. Knoldus Software LLP The conf/routes file # Home page GET / controllers.Application.index GET - Request Type ( GET , POST , ... ). / - URL pattern. Application - The controller object. Index - Method (Action) which is being called.
  • 16. Knoldus Software LLP The template engine ➢ Based on Scala ➢ Compact, expressive, and fluid ➢ Easy to learn ➢ Play Scala template is a simple text file, that contains small blocks of Scala code. They can generate any text- based format, such as HTML, XML or CSV. ➢ Compiled as standard Scala functions.
  • 17. Knoldus Software LLP ● Because Templates are compiled, so you will see any errors right in your browser
  • 18. @main ● views/main.scala.html template act as a main layout template. e.g This is our Main template. @(title: String)(content: Html) <!DOCTYPE html> <html> <head> <title>@title</title> </head> <body> <section class="content">@content</section> </body> </html>
  • 19. ● As you can see, this template takes two parameters: a title and an HTML content block. Now we can use it from any other template e.g views/Application/index.scala.html template: @main(title = "Home") { <h1>Home page</h1> } Note: We sometimes use named parameters(like @main(title = "Home"), sometimes not like@main("Home"). It is as you want, choose whatever is clearer in a specific context.
  • 20. Syntax : the magic ‘@’ character Every time this character is encountered, it indicates the begining of a Scala statement. @employee.name // Scala statement starts here Template parameters A template is simply a function, so it needs parameters, which must be declared on the first line of the template file. @(employees: List[Employee], employeeForm: Form[String])
  • 21. Iterating : You can use the for keyword in order to iterate. <ul> @for(c <- customers) { <li>@c.getName() ($@c.getCity())</li> } </ul> If-blocks : Simply use Scala’s standard if statement: @if(customers.isEmpty()) { <h1>Nothing to display</h1> } else { <h1>@customers.size() customers!</h1> }
  • 22. Compile time checking by Play - HTTP routes file - Templates - Javascript files - Coffeescript files - LESS style sheets
  • 23. HTTP Form The play.api.data package contains several helpers to handle HTTP form data submission and validation. The easiest way to handle a form submission is to define a play.api.data.Form structure:
  • 24. Lets understand it by a defining simple form object FormExampleController extends Controller { val loginForm = Form( tuple( "email" -> nonEmptyText, "password" -> nonEmptyText)) } This form can generate a (String, String) result value from Map[String, String] data:
  • 25. The corresponding template @(loginForm :Form[(String, String)],message:String) @import helper._ @main(message){ @helper.form(action = routes.FormExampleController.authenticateUser) { <fieldset> <legend>@message</legend> @inputText( loginForm("email"), '_label -> "Email ", '_help -> "Enter a valid email address." ) @inputPassword( loginForm("password"), '_label -> "Password", '_help -> "A password must be at least 6 characters." ) </fieldset> <input type="submit" value="Log in "> } }
  • 26. Putting the validation ● We can apply the validation at the time of defining the form controls like : val loginForm = Form( tuple( "email" -> email, "password" -> nonEmptyText(minLength = 6))) ● email means : The textbox would accept an valid Email. ● nonEmptyText(minLength = 6) means : The textbox would accept atleast 6 characters
  • 27. Constructing complex objects You can use complex form mapping as well. Here is the simple example : case class User(name: String, age: Int) val userForm = Form( mapping( "name" -> text, "age" -> number)(User.apply)(User.unapply))
  • 28. Calling WebServices ● Sometimes there becomes a need to call other HTTP services from within a Play application. ● This is supported in Play via play.api.libs.ws.WS library, which provides a way to make asynchronous HTTP calls. ● It returns a Promise[play.api.libs.ws.Response].
  • 29. Making an HTTP call ● GET request : val returnedValue : Promise[ws.Response] = WS.url("http://mysite.com").get() ● POST request : WS.url("http://mysite.com").post(Map("key" -> Seq("value")))
  • 30. Example ● Lets make a WS GET request on ScalaJobz.com API. ● Result : This call would return the JSON of jobs from scalajobz.com.
  • 31. ● Route definition: GET /jobs controllers.Application.jobs ● Controller : /** * Calling web services */ def jobs = Action { WS.url("http://www.scalajobz.com/getAllJobs").get().map { response => println(response.json) } Ok("Jobs Fetched") }
  • 32.
  • 33. Working with XML ● An XML request is an HTTP request using a valid.An XML request is an HTTP request using a valid. XML payload as the request body.XML payload as the request body. ● It must specify theIt must specify the text/xmltext/xml MIME type in itsMIME type in its Content-TypeContent-Type header.header. ● By default anBy default an ActionAction uses a any content bodyuses a any content body parser, which lets you retrieve the body as XMLparser, which lets you retrieve the body as XML (as a NodeSeq)(as a NodeSeq)
  • 34. Defining The Route : POST /sayHello controllers.Application.sayHello Defining The Controller : package controllers import play.api.mvc.Action import play.api.mvc.Controller object Application extends Controller { def sayHello = Action { request => request.body.asXml.map { xml => (xml "name" headOption).map(_.text).map { name => Ok("Hello " + name + " ") }.getOrElse { BadRequest("Missing parameter [name]") } }.getOrElse { BadRequest("Expecting Xml data") } } }
  • 35. Let us make a POST request containing XML data
  • 36. Working with JSON 1. A JSON request is an HTTP request using a valid JSON1. A JSON request is an HTTP request using a valid JSON payload as request body.payload as request body. 2. It must specify the text/json or application/json mime type2. It must specify the text/json or application/json mime type in its Content-Type header.in its Content-Type header. 3. By default an Action uses an any content body parser,3. By default an Action uses an any content body parser, which lets you retrieve the body as JSON.which lets you retrieve the body as JSON. (as a JsValue).(as a JsValue).
  • 37. Defining The Route : POST /greet controllers.Application.greet Defining The Controller : package controllers import play.api.mvc.Controller import play.api.mvc.Action object Application extends Controller { def greet = Action { request => request.body.asJson.map { json => (json "name").asOpt[String].map { name => Ok("Hello " + name + " ") }.getOrElse { BadRequest("Missing parameter [name]") } }.getOrElse { BadRequest("Expecting Json data") } } }
  • 38. Lets make a POST request containing JSON data
  • 40. Knoldus Software LLP Prerequisites 1. Download the Scala SDK from here. http://scala-ide.org/download/sdk.html 2. A basic knowledge of the Eclipse user interface
  • 41. Knoldus Software LLP Setting up Play 2.1 1. Download Play framework 2.1.3 from http://www.playframework.org. 2. Unzip it in your preferred location. Let's say /path/to/play for the purpose of this document. 3. Add the Play folder to your system PATH export PATH=$PATH:/path/to/play
  • 42. Knoldus Software LLP Creating a Play 2.1.3 application In your development folder, ask Play to create a new web application, as a simple Scala application.
  • 44. Knoldus Software LLP ● Clone MyOffice app from here as git clone git@github.com:knoldus/ScalaTraits-August2013-Play.git
  • 45. Knoldus Software LLP Importing the project in to eclipse IDE
  • 47. Knoldus Software LLP The Project Structure
  • 48. Knoldus Software LLP The project “MyOffice” mainly contains : ● app / : Contains the application’s core, split between models, controllers and views directories. ● Conf / : Contains the configuration files. Especially the main application.conf file,the routes definition files. routes defines the routes of the UI calls.
  • 49. Knoldus Software LLP ● project :: Contains the build scripts. ● public / :: Contains all the publicly available resources, which includes JavaScript, stylesheets and images directories. ● test / :: Contains all the application tests.
  • 50. Knoldus Software LLP Edit the conf/routes file: # Home page GET / controllers.Application.index # MyOffice GET /employees controllers.MyOfficeController.employees POST /newEmployee controllers.MyOfficeController.newEmployee POST /employee/:id/deleteEmployee controllers.MyOfficeController.deleteEmployee(id: Long)
  • 51. Knoldus Software LLP Add the MyOfficeController.scala object under controllers & define the methods those will perform the action. package controllers import play.api.mvc._ object MyOfficeController extends Controller { /** * Total Employees In Office */ def employees = TODO /** * Add A New Employee */ def newEmployee = TODO /** * Remove An Employee */ def deleteEmployee(id: Long) = TODO }
  • 52. Knoldus Software LLP ● As you see we use TODO to define our action implementations. Because we haven't write the action implementations yet, we can use the built-in TODO action that will return a 501 Not Implemented HTTP response. Now lets hit the http://localhost:9000/employees & see what we find.
  • 53. Knoldus Software LLP ● Lets define the models in our MyOffice application that will perform the business logic. Preparing the Employee model Before continuing the implementation we need to define how the Employee looks like in our application. Create a case class for it in the app/models/Employee.scala file.e. case class Employee(id: Long, name : String) Each Employee is having an : ● Id - That uniquely identifies the Employee ● name - Name of the Employee
  • 54. Knoldus Software LLP The Employee model package models case class Employee(id: Long, name: String) object Employee { /** * All Employees In Office */ def allEmployees(): List[Employee] = Nil /** * Adding A New Employee */ def newEmployee(nameOfEmployee: String) {} /** * Delete Employee * @param id : id Of The Employee To Be Deleted */ def delete(id: Long) {} }
  • 55. Knoldus Software LLP Now we have our : - Controller MyOfficeController.scala - Model Employee.scala Lets write Application template employee.scala.html. The employee form : Form object encapsulates an HTML form definition, including validation constraints. Let’s create a very simple form in the Application controller: we only need a form with a single name field. The form will also check that the name provided by the user is not empty.
  • 56. Knoldus Software LLP The employee form in MyOfficeController.scala val employeeForm = Form( "name" -> nonEmptyText) The employee form in MyOfficeController.scalaThe employee form in MyOfficeController.scala The type of employeeForm is the Form[String] since it is a form generating a simple String. You also need to Import some play.api.data classes.
  • 57. Knoldus Software LLP @(employees: List[Employee], employeeForm: Form[String]) @import helper._ @main("My Office") { <h1>Presently @employees.size employee(s)</h1> <ul> @employees.map { employee => <li> @employee.name @form(routes.MyOfficeController.deleteEmployee(employee.id)) { <input type="submit" value="Remove Employee"> } </li> } </ul> <h2>Add a new Employee</h2> @form(routes.MyOfficeController.newEmployee) { @inputText(employeeForm("name")) <input type="submit" value="Add Employee"> } }
  • 58. Knoldus Software LLP Rendering the employees.scala.html page Assign the work to the controller method employees. /** * Total Employees In Office */ def employees = Action { Ok(views.html.employee(Employee.allEmployees(), employeeForm)) } ● Now hit the http://localhost:9000/employees and see what happens.
  • 60. Knoldus Software LLP Form Submission ● For now, if we submit the employee creation form, we still get theFor now, if we submit the employee creation form, we still get the TODO page. Let’s write the implementation of theTODO page. Let’s write the implementation of the newEmployeenewEmployee action :action : def newEmployee = Action { implicit request => employeeForm.bindFromRequest.fold( errors => BadRequest(views.html.employee(Employee.allEmployees(), employeeForm)), name => { Employee.newEmployee(name) Redirect(routes.MyOfficeController.employees) }) }
  • 61. Knoldus Software LLP Persist the employees in a database ● It’s now time to persist the employees in a database to make the application useful. Let’s start by enabling a database in our application. In the conf/application.conf file, add: db.default.driver=org.h2.Driver db.default.url="jdbc:h2:mem:play" For now we will use a simple in memory database using H2. No need to restart the server, refreshing the browser is enough to set up the database.
  • 62. Knoldus Software LLP ● We will use Anorm in this tutorial to query the database. First we need to define the database schema. Let’s use Play evolutions for that, so create a first evolution script in conf/evolutions/default/1.sql: # Employees schema # --- !Ups CREATE SEQUENCE employee_id_seq; CREATE TABLE employee ( id integer NOT NULL DEFAULT nextval('employee_id_seq'), name varchar(255) ); # --- !Downs DROP TABLE employee; DROP SEQUENCE employee_id_seq;
  • 63. Knoldus Software LLP Now if you refresh your browser, Play will warn you that your database needs evolution:
  • 64. Knoldus Software LLP ● It’s now time to implement the SQL queries in the Employee companion object, starting with the allEmployees() operation. Using Anorm we can define a parser that will transform a JDBC ResultSet row to a Employee value: import anorm._ import anorm.SqlParser._ val employee = { get[Long]("id") ~ get[String]("name") map { case id ~ name => Employee(id, name) } } Here, employee is a parser that, given a JDBC ResultSet rowHere, employee is a parser that, given a JDBC ResultSet row with at least an id and a name column, is able to create awith at least an id and a name column, is able to create a Employee value.Employee value.
  • 65. Knoldus Software LLP Let us write the implementation of our methods in Employee model. /** * Add A New Employee */ def newEmployee = Action { implicit request => employeeForm.bindFromRequest.fold( errors => BadRequest(views.html.employee(Employee.allEmployees(), employeeForm)), name => { Employee.newEmployee(name) Redirect(routes.MyOfficeController.employees) }) } /** * Remove An Employee */ def deleteEmployee(id: Long) = Action { Employee.delete(id) Redirect(routes.MyOfficeController.employees) }
  • 66. Knoldus Software LLP The model methods /** * All Employees In Office */ def allEmployees(): List[Employee] = DB.withConnection { implicit c => SQL("select * from employee").as(employee *) } /** * Adding A New Employee */ def newEmployee(nameOfEmployee: String) { DB.withConnection { implicit c => SQL("insert into employee (name) values ({name})").on( 'name -> nameOfEmployee).executeUpdate() } } /** * Delete Employee * @param id : id Of The Employee To Be Deleted */ def delete(id: Long) { DB.withConnection { implicit c => SQL("delete from employee where id = {id}").on( 'id -> id).executeUpdate() } }
  • 68. Knoldus Software LLP Let us use the Application “MyOffice”
  • 69. Knoldus Software LLP Lets deploy the App to
  • 70. Knoldus Software LLP Heroku needs a file named ‘Procfile‘ for each application to be deployed on it. What is Procfile ? Procfile is a mechanism for declaring what commands are run when your web or worker dynos are run on the Heroku platform.
  • 71. Knoldus Software LLP Procfile content : web: target/start -Dhttp.port=$PORT -DapplyEvolutions.default=true
  • 72. Knoldus Software LLP Lets Deploy our application 1. Create a file Procfile and put it in the root of your project directory. 2. Initiate the git session for your project and add files to git as git init git add .
  • 73. Knoldus Software LLP 3. Commit the changes for the project to git as git commit -m init 4. On the command line create a new application using the “cedar” stack: heroku create -s cedar 5. Add the git remote : git remote add heroku //TheCloneUrlOnTheHerokuApp//
  • 74. Knoldus Software LLP 6. Application is ready to be deployed to the cloud. push the project files to heroku as: git push heroku master Go to your heroku account -> MyApps and you’ll find a new application that you had just created. Launch the URL and have a look to your running application on heroku. You can also rename your application.