Intoduction to Play Framework

32
Let's With Scala (The Basics) Harsh Sharma Khandal Software Consultant Knoldus Software LLP

Transcript of Intoduction to Play Framework

Let's

With Scala(The Basics)

Harsh Sharma Khandal Software Consultant

Knoldus Software LLP

Agenda

Introduction Overview Various Features of Play Architecture of Play Components of play Action and Result Model, view, controller Routing in play Session tracking and Flash scopes Form Submissions Conclusion

Play is a high-productivity Java and Scala web application framework.

Integrates components and APIs for modern web application development.

Based on a lightweight, stateless, web-friendly architecture and features

Introduction

Requirements for play

Requires a minimum of JDK 1.8

Requires a minimum of sbt 0.13.8

Requires the Typesafe Activator 1.3.5

Overview

Created by Guillaume Bort, at Zengularity(formely Zenexity).

An open source web application framework.

Lightweight, stateless, web-friendly architecture.

Written in Scala and Java.

Support for the Scala programming language.

Various Features of Play

Less configuration: Download, unpack and develop.

Faster Testing

More elegant API

Modular architecture

Asynchronous I/O

Architecture of Play Framework

Architecture of play is stateless.

Each request as an independent transaction.

Each request is unrelated to any previous request so that the communication consists of independent pairs of requests and responses.

Components of Play Framework

Action and Result

Action Most of the requests received by a Play application are handled by an Action. 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 + "]") }

Life cycle of a Request

Results in play

This is how we can show result as in the play.

val ok = Ok("Hello world!")

val notFound = NotFound

val pageNotFound = NotFound(<h1>Page not found</h1>)

val badRequest = BadRequest(views.html.form(formWithErrors))

Results in play

val oops = InternalServerError("Oops")

val anyStatus = Status(488)("Strange response type")

Redirect(“/url”)

Complete Example

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

Base of Play

Play includes the three basic concepts as,

Models Views Controllers

Models

All the logics needed by the events happening on a browser, are kept here

/** * returns a list of even numbers * @param listOfNum * @return list of numbers */

def findEvenNumbers(listOfNum: List[Int]): List[Int] = { listOfNum.filter { element => element % 2 == 0 } }

Views

Views are the users' perspective, something which is visible to the users in on the browser.

Controllers

Controllers are the collection of actions and results required to respond to any request made by a page.

Routing in play

A router is a component that translate incoming HTTP request to an Action.

An HTTP request is taken as an event by MVC framework,

HTTP request contains,

the request path including the query string (e.g. /clients/1542, /photos/list)

the HTTP method (e.g. GET, POST, …)

Routing in play

Routing in play may refer to the following,

HTTP Routing, Javascript Routing

HTTP Routing

# Home pageGET / controllers.Application.indexGET /candidate controllers.Application.indexCandidateGET /candidate/home controllers.Application.candidateHome GET /error controllers.Application.errorGET /aboutUs controllers.Application.aboutUs

# User authenticationGET /login controllers.AuthController.login(userType: String)GET /logout controllers.AuthController.logoutPOST /authenticate controllers.AuthController.authenticate(userType: String)

Javascript RoutingJavascript Routing

Play router has the ability to generate Javascript code.

Purpose behind this is to handle Javascript running client side, back to your application.

Javascript Routing

def isEmailExist(email: String): Action[play.api.mvc.AnyContent] = Action { implicit request => Logger.info("UserController:isEmailExist - Checking user is exist or not with : " + email) val isExist = userService.isEmailExist(email) if (isExist) { Ok("true") } else { Ok("false") } }

#RegistrationsGET /registerForm controllers.UserController.registerForm(userType: String)GET /isEmailExist controllers.UserController.isEmailExist(email: String)POST /register controllers.UserController.registerGET /recruiteForm controllers.UserController.registerRecruiterForm(userType: String)POST /registerRecruiter controllers.UserController.registerRecruiter

Javascript Routing

function isEmailExist(email) { var ajaxCallback = { success: successAjaxTags, error: errorAjaxTags };jsRoutes.controllers.UserController.isEmailExist(email).ajax(ajaxCallback);}

Javascript Routing

var successAjaxTags = function(data){ if(data == true){ // to do section }}

var errorAjaxTags = function(err){ console.log("Unable to find email:"+err)}

Session Tracking and Flash Scopes

Session is about where data that is kept for accessing across multiple HTTP requests.

Data in a session is valid unless the session is invalidated or expired.

Flash scopes are like sessions to store data.

Unlike sessions, flash scope keeps the data for the next request, which is made.

As the request is given a response, flash scope expires.

HTTP Session

Creating a new session

Ok("Welcome!").withSession("connected" -> "[email protected]")

Redirect(routes.AdminController.users).withSession("connected" -> "[email protected]")

Reading a session value

val email = request.session.get("connected").getOrElse("")

Destroy a session

Ok("you have successfully logged in!!!").withNewSession

Flash Scope

Creating a flash scope

Ok(views.html.index).render( "myDashboard", play.api.mvc.Flash(Map("success" -> "you have successfully logged in !")))

Form Submissions

defining a form,

defining constraints in the form,

validating the form in an action,

displaying the form in a view template,

and finally, processing the result (or errors) of the form in a view template.

The basic steps to be followed in performing operations with a form

Form Submissions

In controller, we define a form as,

Form Submissions

val loginForm = Form( mapping( "email" -> email, "password" -> nonEmptyText, "keepLoggedIn" -> optional(text) )(LogIn.apply)(LogIn.unapply))

case class LogIn( email: String, password: String, keepLoggedIn: Option[String])

Conclusion

Play framework provides a better way to create scalable and web friendly applications.

Follows the Model-View-Controller approach to keep the programming modulating.

Testing in play is faster than others as it provides environment to use different api's.