Top Banner
Let's With Scala (The Basics) Harsh Sharma Khandal Software Consultant Knoldus Software LLP
32
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Intoduction to Play Framework

Let's

With Scala(The Basics)

Harsh Sharma Khandal Software Consultant

Knoldus Software LLP

Page 2: Intoduction to Play Framework

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

Page 3: Intoduction to Play Framework

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

Page 4: Intoduction to Play Framework

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

Page 5: Intoduction to Play Framework

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.

Page 6: Intoduction to Play Framework

Various Features of Play

Less configuration: Download, unpack and develop.

Faster Testing

More elegant API

Modular architecture

Asynchronous I/O

Page 7: Intoduction to Play Framework

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.

Page 8: Intoduction to Play Framework

Components of Play Framework

Page 9: Intoduction to 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 + "]") }

Page 10: Intoduction to Play Framework

Life cycle of a Request

Page 11: Intoduction to Play Framework

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))

Page 12: Intoduction to Play Framework

Results in play

val oops = InternalServerError("Oops")

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

Redirect(“/url”)

Page 13: Intoduction to Play Framework

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

Page 14: Intoduction to Play Framework

Base of Play

Play includes the three basic concepts as,

Models Views Controllers

Page 15: Intoduction to Play Framework

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 } }

Page 16: Intoduction to Play Framework

Views

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

Page 17: Intoduction to Play Framework

Controllers

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

Page 18: Intoduction to Play Framework

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, …)

Page 19: Intoduction to Play Framework

Routing in play

Routing in play may refer to the following,

HTTP Routing, Javascript Routing

Page 20: Intoduction to Play Framework

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)

Page 21: Intoduction to Play Framework

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.

Page 22: Intoduction to Play Framework

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

Page 23: Intoduction to Play Framework

Javascript Routing

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

Page 24: Intoduction to Play Framework

Javascript Routing

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

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

Page 25: Intoduction to Play Framework

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.

Page 26: Intoduction to Play Framework

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

Page 27: Intoduction to Play Framework

Flash Scope

Creating a flash scope

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

Page 28: Intoduction to Play Framework

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

Page 29: Intoduction to Play Framework

Form Submissions

Page 30: Intoduction to Play Framework

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])

Page 31: Intoduction to Play Framework

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.

Page 32: Intoduction to Play Framework