SlideShare a Scribd company logo
1 of 45
Download to read offline
Business Informatics Group
Institute of Software Technology and Interactive Systems
Vienna University of Technology
Favoritenstraße 9-11/188-3, 1040 Vienna, Austria
phone: +43 (1) 58801-18804 (secretary), fax: +43 (1) 58801-18896
office@big.tuwien.ac.at, www.big.tuwien.ac.at
Play Framework: The Basics
Building scalable web applications based on a non-blocking, stateless
architecture and the Java Persistence API
Philip Langer
Outline
1. Motivation and overview
2. Setup and project structure
3. Controllers and routing
4. Templates with Scala
5. Models and JPA
6. Forms and server-side validation
7. Internationalization
8. Authentication
9. Client state on the server
10.Asynchronous results
Motivation and Overview
3
ī‚§ Goals of the Play framework
ī‚§ Stateless web framework
ī‚§ As opposed to stateful
ī‚§ Based on an “evented” web server architecture
ī‚§ As opposed to threaded
ī‚§ Full-stack web framework
ī‚§ Including model persistence, template mechanism (view), controller, and testing
ī‚§ Aims at being
ī‚§ “developer-friendly” (e.g., hot reload mimicking interpreted languages)
ī‚§ fully compiled and type safe (even templates and routes)
ī‚§ Further nice features
ī‚§ RESTful by default
ī‚§ Integration of JSON
ī‚§ Integration of compilers for CoffeeScript, LESS, etc.
ī‚§ Support for long-living connections (WebSocket, Comet, â€Ļ)
ī‚§ â€Ļ
Motivation and Overview
4
ī‚§ Stateful versus stateless web frameworks
ī‚§ Traditional web frameworks are stateful
Server-side state is stored for each client in a session
Web
Server DB
Motivation and Overview
5
ī‚§ Stateful versus stateless web frameworks
ī‚§ Traditional web frameworks are stateful
Server-side state is stored for each client in a session
Web
Server DB
Motivation and Overview
6
ī‚§ Stateful versus stateless web frameworks
ī‚§ Traditional web frameworks are stateful
Server-side state is stored for each client in a session
Load
Balancer
Web
Server
Web
Server DB
Web
Server
?
Motivation and Overview
7
ī‚§ Stateful versus stateless web frameworks
ī‚§ Traditional web frameworks are stateful
Server-side state is stored for each client in a session
Load
Balancer
Web
Server
Web
Server DB
Web
Server
DB
Motivation and Overview
8
ī‚§ Stateful versus stateless web frameworks
ī‚§ Recently stateless web frameworks gained popularity
ī‚§ Web server instances do not store user state (“shared nothing”)
ī‚§ Stateful client & shared cache (memcached, MongoDB, â€Ļ)
ī‚§ Allows to do horizontal scaling (adding/removing web server instances)
Load
Balancer
Web
Server
Web
Server
Web
Server DB
DB
Motivation and Overview
9
ī‚§ Threaded versus evented web servers
ī‚§ Thread pool maintains a number of threads
ī‚§ For each request, a thread is allocated until the request is completed
Load
Balancer
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
DB
Motivation and Overview
10
ī‚§ Threaded versus evented web servers
ī‚§ Thread pool maintains a number of threads
ī‚§ For each request, a thread is allocated until the request is completed
ī‚§ Thread is occupied but potentially idle
due to long-running requests to other services
Load
Balancer
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
StockService s1 = new StockService();
PricingService s2 = new PricingService();
List<Stock> stocks = s1.requestStocks();
List<Price> prices = new ArrayList<long>();
for (Stock stock : stocks) {
long price = s2.getPrice(stock.getId());
prices.add(price);
}
// ...
renderResponse(response, prices);
}
DB
Motivation and Overview
11
ī‚§ Threaded versus evented web servers
ī‚§ Thread pool maintains a number of threads
ī‚§ For each request, a thread is allocated until the request is completed
ī‚§ Thread is occupied but potentially idle
due to long-running requests to other services
Load
Balancer
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
When latency goes up here,
threads are all occupied soon
īƒ  new requests are queued.
DB
Motivation and Overview
12
ī‚§ Threaded versus evented web servers
ī‚§ Thread pool maintains a number of threads
ī‚§ For each request, a thread is allocated until the request is completed
ī‚§ Thread is occupied but potentially idle
due to long-running requests to other services
Load
Balancer
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Latency goes up here too,
threads get all occupied
īƒ  new requests are queued too.
DB
Motivation and Overview
13
ī‚§ Threaded versus evented web servers
ī‚§ Thread pool maintains a number of threads
ī‚§ For each request, a thread is allocated until the request is completed
ī‚§ Thread is occupied but potentially idle
due to long-running requests to other services
Load
Balancer
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
Web
Server
same hereâ€Ļ
and hereâ€Ļ
and hereâ€Ļ
and hereâ€Ļ
and hereâ€Ļ
Motivation and Overview
14
ī‚§ Threaded versus evented web servers
ī‚§ Play is based on Netty
An event-driven client-server framework
ī‚§ Play is based on Akka and the Promise/Future API
Software library for building concurrent applications
ī‚§ For each CPU core, there is one thread/process
ī‚§ Enables asynchronous, non-blocking server requests/responses
īƒ  Thread is occupied only, if there is something to do
īƒ  No sensitivity to downstream latency
Motivation and Overview
15
ī‚§ Full-stack framework
ī‚§ Model-view-controller architecture
ī‚§ Model and controller can be realized with Java or Scala
ī‚§ View is realized with a template syntax and Scala
ī‚§ Model persistence is based on Ebean by default
ī‚§ But any other persistence mechanism can be used too
ī‚§ We will use the Java Persistence API instead
ī‚§ Play integrates unit, integration, and system testing tools
ī‚§ JUnit
ī‚§ Dedicated APIs to call controllers and views
ī‚§ Selenium WebDriver and FluentLenium
Motivation and Overview
16
ī‚§ Developer friendliness
ī‚§ Aims at combining the benefits of
ī‚§ Frameworks using interpreted languages (no compile/deploy/test delay)
ī‚§ Type safety and checks of compiled languages
ī‚§ Hot reload
ī‚§ Framework listens for changes and compiles & deploys in background
ī‚§ Change something, hit refresh in the browser, and you will see the effect
ī‚§ Compiled, static-typed language is used
ī‚§ Java or Scala
ī‚§ Also templates and routes are type checked
Setup and project structure
17
Create a new play project
$ play new ewa-play-intro
_
_ __ | | __ _ _ _
| '_ | |/ _' | || |
| __/|_|____|__ /
|_| |__/
play 2.2.1 built with Scala 2.10.2 (running Java 1.7.0_25), http://www.playframework.com
The new application will be created in /home/whatever/ewa-play-intro
What is the application name? [ewa-play-intro]
Which template do you want to use for this new application?
1 - Create a simple Scala application
2 - Create a simple Java application
> 2
OK, application ewa-play-intro is created.
Have fun!
https://github.com/planger/ewa-play-intro/tree/a616c8b
Setup and project structure
18
The play console
Open the project folder (i.e., ewa-play-intro) in a console and start play
$ play
â€Ļ
[ewa-play-intro] $ help play
These commands are available:
-----------------------------
classpath Display the project classpath.
clean Clean all generated files.
compile Compile the current application.
console Launch the interactive Scala console (use :quit to exit).
dependencies Display the dependencies summary.
dist Construct standalone application package.
exit Exit the console.
h2-browser Launch the H2 Web browser.
license Display licensing informations.
package Package your application as a JAR.
play-version Display the Play version.
publish Publish your application in a remote repository.
publish-local Publish your application in the local repository.
reload Reload the current application build file.
run <port> Run the current application in DEV mode.
test Run Junit tests and/or Specs from the command line
eclipse generate eclipse project file
idea generate Intellij IDEA project file
sh <command to run> execute a shell command
start <port> Start the current application in another JVM in PROD mode.
update Update application dependencies.
https://github.com/planger/ewa-play-intro/tree/a616c8b
Setup and project structure
19
Setup the IDE (Eclipse or IntelliJ) // you can also use any editor you like (compiling is done by Play)
[ewa-play-intro] $ eclipse
[info] About to create Eclipse project files for your project(s).
[info] Successfully created Eclipse project files for project(s):
[info] ewa-play-intro
In Eclipse
Import īƒ  Existing Projects into Workspace īƒ  Select
https://github.com/planger/ewa-play-intro/tree/a616c8b
Setup and project structure
20
Project structure
ī‚§ app/
contains the application’s core in models, controllers, and views directories.
ī‚§ conf/
contains all the application’s configuration files, especially the application.conf
file, the routes definition files, and the messages files used for internationalization.
ī‚§ project/
contains the build scripts.
ī‚§ public/
contains all the publicly available resources: JavaScript, stylesheets, and images.
ī‚§ test/
contains all the application’s tests.
https://github.com/planger/ewa-play-intro/tree/a616c8b
Setup and project structure
21
Run the application
[ewa-play-intro] $ run
[info] Updating {file:/home/whatever/ewa-play-intro/}ewa-play-intro...
[info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin[info]
Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
--- (Running the application from SBT, auto-reloading is enabled) ---
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Ctrl+D to stop and go back to the console...)
https://github.com/planger/ewa-play-intro/tree/a616c8b
Setup and project structure
22
Run the application
[ewa-play-intro] $ run
[info] Updating {file:/home/whatever/ewa-play-intro/}ewa-play-intro...
[info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin[info]
Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
--- (Running the application from SBT, auto-reloading is enabled) ---
[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
(Server started, use Ctrl+D to stop and go back to the console...)
https://github.com/planger/ewa-play-intro/tree/a616c8b
Controllers and Routing
23
ī‚§ Controller are static classes
ī‚§ Located in app/controllers
ī‚§ Inherit from an abstract Controller class
ī‚§ Access to methods for obtaining request and sending back requests
ī‚§ request().remoteAddress() īƒ  Access Request object and obtains address
ī‚§ ok("Hello") īƒ  Result “x” with HTTP status 200
ī‚§ Public static methods are also called “actions”
ī‚§ Take arbitrary parameters
ī‚§ Return Result object
public static Result sayHello() {
return ok("Hello " + request().remoteAddress());
}
public static Result sayHelloTo(String name) {
if (name.toLowerCase().matches("[a-z]")) {
String theName = name.toUpperCase();
return ok("Hello " + theName);
} else {
return badRequest("Provide a proper name!");
}
}
http://www.playframework.com/documentation/2.0/JavaActions
https://github.com/planger/ewa-play-intro/tree/ef1891c
Controllers and Routing
24
ī‚§ Routing maps incoming requests to controller actions
ī‚§ Syntax: <HTTPMethod> <URIPattern> <ControllerAction>
ī‚§ HTTPMethod: GET, POST, DELETE, â€Ļ
ī‚§ Configured in conf/routes
ī‚§ Routes are compiled and type safe too!
ī‚§ URI patterns support
ī‚§ Variable extraction (:name)
ī‚§ Dynamic parts spanning several / (path*)
ī‚§ Regular expressions ($name<[a-z]>)
ī‚§ Controller actions support default values
# in conf/routes
GET /anonymoushello controllers.Application.sayHello()
GET /hello controllers.Application.sayHelloTo(name: String = "Stranger")
GET /hello/:name controllers.Application.sayHelloTo(name: String)
http://www.playframework.com/documentation/2.0/JavaRouting
https://github.com/planger/ewa-play-intro/tree/ef1891c
Templates with Scala
25
ī‚§ Templates
ī‚§ Located in app/views/
ī‚§ Named *.scala.<format>
ī‚§ Templates are compiled and are type-checked
ī‚§ Example:
app/views/index.scala.html īƒ  class named views.html.index
To render a template from within a controller:
â€Ļ
import views.html.*;
â€Ļ
public static Result index() {
return ok(index.render("Your new application is ready."));
}
https://github.com/planger/ewa-play-intro/tree/ef1891c
Templates with Scala
26
ī‚§ Templates
ī‚§ They are basically Scala functions
ī‚§ They may take parameters
ī‚§ They may call other functions
ī‚§ Static content mixed with Scala code using @
In main.scala.html
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
<link rel="stylesheet" media="screen"
href="@routes.Assets.at("stylesheets/main.css")">
</head>
<body> @content </body>
</html>
http://www.playframework.com/documentation/2.0/JavaTemplates
https://github.com/planger/ewa-play-intro/tree/ef1891c
Templates with Scala
27
ī‚§ Templates
ī‚§ They are basically Scala functions
ī‚§ They may take parameters
ī‚§ They may call other functions
ī‚§ Static content mixed with Scala code using @
In main.scala.html
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
<link rel="stylesheet" media="screen"
href="@routes.Assets.at("stylesheets/main.css")">
</head>
<body> @content </body>
</html>
http://www.playframework.com/documentation/2.0/JavaTemplates
Reverse routing
GET /assets/*file controllers.Assets.at(path="/public", file)
https://github.com/planger/ewa-play-intro/tree/ef1891c
Templates with Scala
28
ī‚§ Templates
ī‚§ They are basically Scala functions
ī‚§ They may take parameters
ī‚§ They may call other functions
ī‚§ Static content mixed with Scala code using @
In main.scala.html
@(title: String)(content: Html)
<!DOCTYPE html>
â€Ļ @content â€Ļ
In another.scala.html
@(message: String)
@main("This is the title of type String") {
<h1>This is the content of type Html</h1> <p>@message</p>
}
http://www.playframework.com/documentation/2.0/JavaTemplates
https://github.com/planger/ewa-play-intro/tree/ef1891c
Templates with Scala
29
ī‚§ Example
app/controllers/Application.java
public static Result listCharacters(String text) {
List<Character> characters = new ArrayList<Character>();
for (char c : text.toLowerCase().toCharArray())
if (!characters.contains(c))
characters.add(c);
return ok(characterlist.render(text, characters));
}
app/views/characterlist.scala.html
@(text: String, characters: List[Character])
<!DOCTYPE html>
<html>
<head> <title>@text</title> </head>
<body>
<h1>Characters of @text</h1>
@charactersAsUnorderedList(characters)
</body>
</html>
@charactersAsUnorderedList(characters: List[Character]) = {
@if(!characters.isEmpty()) {
<ul>
@for(character <- characters) {
<li>@character</li>
}
</ul>
}
}
https://github.com/planger/ewa-play-intro/tree/c1b1594
Models and JPA
30
ī‚§ Models
ī‚§ Java or Scala classes that should be located in app/models/
ī‚§ Represent the domain model (cf. MVC pattern)
ī‚§ Basically, they are plain old Java objects
ī‚§ Nothing special to be considered for working with them in Play
ī‚§ Model objects are usually persisted in a database
ī‚§ Play integrates Ebean1 by default (ORM persistence layer)
ī‚§ But any other persistence layer may be used instead
ī‚§ In this lecture, we use JPA2 & Hibernate3
īƒ  A brief excursus on object/relational mapping (ORM), JPA, and Hibernate
1 http://www.avaje.org/
2 http://www.oracle.com/technetwork/java/javaee/tech/persistence-jsp-140049.html
3 http://hibernate.org/orm/
JPA: Java Persistence API
31
ī‚§ API for managing the persistence of a Java domain model
ī‚§ Object/relational mapping
ī‚§ Java objects are persisted in a relational database
ī‚§ Standardized under the Java Community Process Program
ī‚§ Annotations for specifying persistent entities
ī‚§ Object/relational mapping metadata
ī‚§ API for storing, querying, and deleting objects
ī‚§ Java Persistence Query Language (JPQL)
ī‚§ Several JPA providers available
ī‚§ Hibernate
ī‚§ EclipseLink
ī‚§ Apache OpenJPA
JPA: Persistent Entities
32
ī‚§ Annotated Plain Old Java Objects
ī‚§ Lightweight persistent domain object
ī‚§ Persistent identity field
ī‚§ Typically EJB style classes
ī‚§ Public or protected no-arg constructor
ī‚§ Getters and setters
ī‚§ Support for
ī‚§ Abstract classes and inheritance
ī‚§ Relationships (OneToOne, OneToMany, ManyToMany)
ī‚§ Each entity is typically represented by one table
ī‚§ Each instance of an entity corresponds to a row in that table
ī‚§ Entities may have both persistent and non-persistent state
ī‚§ Persistent simple or complex typed data
ī‚§ Non-persistent state (transient)
JPA: Persistent Entity
33
ī‚§ Example
@Entity
@Access(AccessType.FIELD)
public class Employee {
@Id
private long id;
private String name;
@Transient
private Money salary;
@ManyToOne(fetch=FetchType.LAZY)
private Employee manager;
@Access(AccessType.PROPERTY)
private BigDecimal getSalary() {
return this.salary.toNumber();
}
private void setSalary(BigDecimal salary) {
this.salary = new Money(salary);
}
}
EMPLOYEE
ID NAME MANAGER_ID SALARY
Models and JPA
34
ī‚§ Integrating Play with JPA and Hibernate
ī‚§ Add dependencies (JPA and hibernate) to build.sbt
ī‚§ Expose the datasource through JNDI in conf/application.conf
ī‚§ Add persistence.xml to conf/META-INF
ī‚§ Add dependency to Eclipse project (just for IDE support)
ī‚§ Project Preferences īƒ  Java Build Path īƒ  Add External Library
ī‚§ Browse to your Play local installation and select
play-2.2.1/repository/local/com.typesafe.play/play-java-jpa_2.10/2.2.1/jars/play-java-jpa_2.10.jar
ī‚§ Reload dependencies in the Play console
$ play reload
http://www.playframework.com/documentation/2.2.x/JavaJPA
https://github.com/planger/ewa-play-intro/tree/15c5b4a
Models and JPA
35
ī‚§ Using JPA in Play
ī‚§ Model class with JPA annotations (javax.persistence.*)
@Entity
public class Pet {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Gender gender;
â€Ļ // getters and setters
ī‚§ Controllers may access the JPA entity manager
ī‚§ Actions have to be annotated with javax.persistence.Transactional
@Transactional
public static Result list() {
Collection<Pet> pets = getAllPets();
return ok(Json.toJson(pets));
}
private static Collection<Pet> getAllPets() {
EntityManager em = play.db.jpa.JPA.em();
String queryString = "SELECT p FROM Pet p";
TypedQuery<Pet> query = em.createQuery(queryString, Pet.class);
return (Collection<Pet>) query.getResultList();
}
http://www.playframework.com/documentation/2.2.x/JavaJPA
https://github.com/planger/ewa-play-intro/tree/d870e86
Forms and server-side validation
36
ī‚§ Creating and processing dynamic forms
ī‚§ Helpers to create HTML forms in templates
@helper.form(action = routes.Pets.createPetResponse) {
<select name="petId">
@for(pet <- pets) {
<option value="@pet.getId()">@pet.getName()</option>
}
</select>
<input type="text" id="petResponse" name="petResponse" />
<button type="submit" name="action" value="new">Respond</button>
}
ī‚§ Helpers to handle HTTP form data in controllers
@Transactional
public static Result createPetResponse() {
DynamicForm form = Form.form().bindFromRequest();
String petId = form.data().get("petId");
String petResponse = form.data().get("petResponse");
Pet pet = getPetById(Long.valueOf(petId));
return ok(pet.getName() + " says " + petResponse);
}
http://www.playframework.com/documentation/2.0/ScalaFormHelpers
http://www.playframework.com/documentation/2.0/JavaForms
https://github.com/planger/ewa-play-intro/tree/75fb91d
Forms and server-side validation
37
ī‚§ Creating and processing forms for model classes
ī‚§ Helpers to create HTML forms in templates
<h1>New pet</h1>
@helper.form(action = routes.Pets.createPet) {
@helper.inputText(form("name"))
@helper.inputRadioGroup( form("gender"), options = Seq(("male"->"Male"),
("female"->"Female")))
<button type="submit" name="action" value="new">Save</button>
}
ī‚§ Helpers to handle HTTP form data in controllers
@Transactional
public static Result createPet() {
Form<Pet> form = Form.form(Pet.class).bindFromRequest();
if (form.hasErrors()) {
return badRequest(petform.render(form));
} else {
Pet pet = form.get();
JPA.em().persist(pet);
return redirect(routes.Pets.list());
}
}
http://www.playframework.com/documentation/2.0/ScalaFormHelpers
http://www.playframework.com/documentation/2.0/JavaForms
https://github.com/planger/ewa-play-intro/tree/75fb91d
Forms and server-side validation
38
ī‚§ Creating and processing forms for model classes
ī‚§ Helpers to create HTML forms in templates
<h1>New pet</h1>
@helper.form(action = routes.Pets.createPet) {
@helper.inputText(form("name"))
@helper.inputRadioGroup( form("gender"), options = Seq(("male"->"Male"),
("female"->"Female")))
<button type="submit" name="action" value="new">Save</button>
}
ī‚§ Helpers to handle HTTP form data in controllers
@Transactional
public static Result createPet() {
Form<Pet> form = Form.form(Pet.class).bindFromRequest();
if (form.hasErrors()) {
return badRequest(petform.render(form));
} else {
Pet pet = form.get();
JPA.em().persist(pet);
return redirect(routes.Pets.list());
}
}
http://www.playframework.com/documentation/2.0/ScalaFormHelpers
http://www.playframework.com/documentation/2.0/JavaForms
<form action="/pets" method="POST">
<dl class=" " id="name_field">
<dt><label for="name">name</label></dt>
<dd> <input type="text" id="name" name="name" value="" > </dd>
</dl>
<dl class=" " id="gender_field">
<dt><label for="gender">gender</label></dt>
<dd>
<span class="buttonset" id="gender">
<input type="radio" id="gender_male" name="gender" value="male" >
<label for="gender_male">Male</label>
<input type="radio" id="gender_female" name="gender" value="female" >
<label for="gender_female">Female</label>
</span>
</dd>
</dl>
<button type="submit" name="action" value="new">Save</button>
</form>
https://github.com/planger/ewa-play-intro/tree/75fb91d
Forms and server-side validation
39
ī‚§ Server-side validation of model classes
ī‚§ Several validation rules available in play.data.validation.Constraints
public class Pet {
â€Ļ
@Constraints.Required
@Constraints.MinLength(4)
@Constraints.MaxLength(8)
private String name;
â€Ļ
ī‚§ Custom validation rules can be specified in a validate method
public List<ValidationError> validate() {
List<ValidationError> errors = null;
if (!Character.isUpperCase(name.charAt(0))) {
errors = new ArrayList<ValidationError>();
errors.add(new ValidationError("name", "Must start with upper case letter"));
}
return errors;
}
http://www.playframework.com/documentation/2.0/JavaForms
https://github.com/planger/ewa-play-intro/tree/9716829
Forms and server-side validation
40
ī‚§ Displaying validation error messages
ī‚§ Redirect back to form in case of an error
if (form.hasErrors()) {
return badRequest(petform.render(form));
}
ī‚§ Validation errors are available in forms for custom messages
@for(error <- form("name").errors) {
<div id="error_msg_name" class="error" role="alert">
@error.message
</div>
}
ī‚§ When using form helpers, error messages are rendered automatically
http://www.playframework.com/documentation/2.0/JavaForms
https://github.com/planger/ewa-play-intro/tree/9716829
Internationalization
41
ī‚§ Specifying supported languages
ī‚§ In conf/application.conf
application.langs=en,de
ī‚§ Externalizing messages
ī‚§ In conf/messages.<langcode>
pet.gender=Geschlecht
pet.response={0} sagt {1}.
ī‚§ Using messages in templates
<div>@Messages("pet.gender")</div>
<div>@Messages("pet.response", pet.getName(), petResponse)</div>
ī‚§ Using messages in Java using play.api.i18n.Messages
Messages.get("pet.gender")
Messages.get("pet.response", pet.getName(), petResponse)
http://www.playframework.com/documentation/2.0/JavaI18N
https://github.com/planger/ewa-play-intro/tree/d1bf60b
Authentication
42
ī‚§ Authentication is realized using action composition
ī‚§ Action composition enables to process actions in a chain
ī‚§ Each action can modify the request before passing it on
ī‚§ It may also decide to not pass the request (e.g., if not authenticated)
ī‚§ Play already provides a built-in authenticator action
ī‚§ Subclass play.mvc.Security.Authenticator
ī‚§ getUsername(Http.Context ctx)
ī‚§ Return null if not authenticated
ī‚§ onUnauthorized(Http.Context ctx)
ī‚§ Decide what to do if unauthorized
ī‚§ Annotate entire controllers or single controller methods (actions)
@Security.Authenticated(<yoursubclass>.class)
public static Result createPet() {â€Ļ}
https://www.playframework.com/documentation/2.2.x/JavaGuide4
Client state on the server
43
ī‚§ Web server is stateless
ī‚§ Sometimes we need to save client state
ī‚§ E.g., to store whether a user is logged in already, shopping cart etc.
ī‚§ Options to store a client state
ī‚§ Session
ī‚§ Stored in a cookie at the client
ī‚§ Limited to 4 KB
ī‚§ Hashed and encrypted (to prohibit manipulation)
ī‚§ In a controller: session("key", "value"); session().remove("key");
ī‚§ Cache
ī‚§ Enables caching of objects and even entire HTTP responses
ī‚§ Should not be used to store irreproducible data (well, it‘s a cache)
ī‚§ In a controller: Cache.set("key", "value"); Cache.get("key");
ī‚§ Datastore
ī‚§ Larger irreproducible data should be stored in a database
https://www.playframework.com/documentation/2.2.x/JavaSessionFlash
https://www.playframework.com/documentation/2.2.x/JavaCache
Asynchronous results
44
ī‚§ Useful for longer running controller actions
ī‚§ E.g., when calling other web services or long-running database queries
ī‚§ Avoids blocking a thread
ī‚§ Play provides Scala‘s Promise API and asynchronous results
ī‚§ A promise is a wrapper of a future value
ī‚§ A Promise<T> will eventually yield the value T (or an error)
ī‚§ For an asynchronous result, return a Promise<Result>
ī‚§ Once the Promise<Result> yields the actual data
the result is sent to the client
public static Promise<Result> longRunningAction() {
Logger.info("Long running action entry");
WSRequestHolder duckduck = WS.url("https://www.duckduckgo.com");
Promise<Response> duckduckResponse = duckduck.get();
Promise<Result> result = duckduckResponse.map(toResult);
Logger.info("Long running action exit");
return result;
}
private static Function<Response, Result> toResult = new Function<Response, Result>() {
public Result apply(Response response) {
Logger.info("Inside the toResult function");
return ok(response.getBody()).as("text/html");
}
};
http://www.playframework.com/documentation/2.0/ScalaFormHelpers
http://www.playframework.com/documentation/2.0/JavaForms
https://github.com/planger/ewa-play-intro/tree/706f06e
References
45
ī‚§ Code of these slides is available at github
ī‚§ https://github.com/planger/ewa-play-intro
ī‚§ Official documentation and tutorials
ī‚§ http://www.playframework.com/documentation/2.2.x/JavaHome
ī‚§ Parts of these slides are based on slides by Yevgeniy Brikman
ī‚§ http://www.slideshare.net/brikis98/play-framework-async-io-with-java-and-scala
ī‚§ https://www.youtube.com/watch?v=8z3h4Uv9YbE
ī‚§ Another nice tutorial on Play
ī‚§ https://www.youtube.com/watch?v=9_YYgl65FLs

More Related Content

What's hot

Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersTeng Shiu Huang
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core javamahir jain
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to SwaggerKnoldus Inc.
 
Qtp Basics
Qtp BasicsQtp Basics
Qtp Basicsmehramit
 
[AUG]개발ėžė™€ QA가 ėƒėƒí•˜ëŠ” 테ėŠ¤íŠ¸ 프로ė„¸ėŠ¤
[AUG]개발ėžė™€ QA가 ėƒėƒí•˜ëŠ” 테ėŠ¤íŠ¸ 프로ė„¸ėŠ¤[AUG]개발ėžė™€ QA가 ėƒėƒí•˜ëŠ” 테ėŠ¤íŠ¸ 프로ė„¸ėŠ¤
[AUG]개발ėžė™€ QA가 ėƒėƒí•˜ëŠ” 테ėŠ¤íŠ¸ 프로ė„¸ėŠ¤ė˛ ë¯ŧ ė‹ 
 
Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".SudhanshuVijay3
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machineNikhil Sharma
 
Meetup React Sanca - 29/11/18 - React Testing
Meetup React Sanca - 29/11/18 - React TestingMeetup React Sanca - 29/11/18 - React Testing
Meetup React Sanca - 29/11/18 - React TestingAugusto Lazaro
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
Introduction to jmeter
Introduction to jmeterIntroduction to jmeter
Introduction to jmetertest test
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Web Servers: Architecture and Security
Web Servers: Architecture and SecurityWeb Servers: Architecture and Security
Web Servers: Architecture and Securitygeorge.james
 
Test Plan for online auction system
Test Plan for online auction systemTest Plan for online auction system
Test Plan for online auction systemKomalah Nair
 
Industrial Training Report on Java Technology.
Industrial Training Report on Java Technology.Industrial Training Report on Java Technology.
Industrial Training Report on Java Technology.Ritesh Kumar Bhanu
 
Android styles and themes
Android   styles and themesAndroid   styles and themes
Android styles and themesDeepa Rani
 

What's hot (20)

Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE Developers
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
Qtp Basics
Qtp BasicsQtp Basics
Qtp Basics
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
[AUG]개발ėžė™€ QA가 ėƒėƒí•˜ëŠ” 테ėŠ¤íŠ¸ 프로ė„¸ėŠ¤
[AUG]개발ėžė™€ QA가 ėƒėƒí•˜ëŠ” 테ėŠ¤íŠ¸ 프로ė„¸ėŠ¤[AUG]개발ėžė™€ QA가 ėƒėƒí•˜ëŠ” 테ėŠ¤íŠ¸ 프로ė„¸ėŠ¤
[AUG]개발ėžė™€ QA가 ėƒėƒí•˜ëŠ” 테ėŠ¤íŠ¸ 프로ė„¸ėŠ¤
 
Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".Summer training presentation on "CORE JAVA".
Summer training presentation on "CORE JAVA".
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Meetup React Sanca - 29/11/18 - React Testing
Meetup React Sanca - 29/11/18 - React TestingMeetup React Sanca - 29/11/18 - React Testing
Meetup React Sanca - 29/11/18 - React Testing
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
J2EE Introduction
J2EE IntroductionJ2EE Introduction
J2EE Introduction
 
Introduction to jmeter
Introduction to jmeterIntroduction to jmeter
Introduction to jmeter
 
Apache jMeter
Apache jMeterApache jMeter
Apache jMeter
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Web Servers: Architecture and Security
Web Servers: Architecture and SecurityWeb Servers: Architecture and Security
Web Servers: Architecture and Security
 
Test Plan for online auction system
Test Plan for online auction systemTest Plan for online auction system
Test Plan for online auction system
 
Industrial Training Report on Java Technology.
Industrial Training Report on Java Technology.Industrial Training Report on Java Technology.
Industrial Training Report on Java Technology.
 
Android styles and themes
Android   styles and themesAndroid   styles and themes
Android styles and themes
 
Api testing
Api testingApi testing
Api testing
 

Similar to Play Framework: The Basics

Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Ido Flatow
 
eXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework IntroductioneXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework Introductionvstorm83
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet backdoor
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applicationshchen1
 
Java EE 7 introduction
Java EE 7  introductionJava EE 7  introduction
Java EE 7 introductionMoumie Soulemane
 
Java ee introduction
Java ee introductionJava ee introduction
Java ee introductionMoumie Soulemane
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundryrajdeep
 
Project report for final year project
Project report for final year projectProject report for final year project
Project report for final year projectsuneel singh
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET PresentationRasel Khan
 
The Play Framework at LinkedIn
The Play Framework at LinkedInThe Play Framework at LinkedIn
The Play Framework at LinkedInYevgeniy Brikman
 
The Play Framework at LinkedIn: productivity and performance at scale - Jim B...
The Play Framework at LinkedIn: productivity and performance at scale - Jim B...The Play Framework at LinkedIn: productivity and performance at scale - Jim B...
The Play Framework at LinkedIn: productivity and performance at scale - Jim B...jaxconf
 
The Top 10 Things Oracle UCM Users Need To Know About WebLogic
The Top 10 Things Oracle UCM Users Need To Know About WebLogicThe Top 10 Things Oracle UCM Users Need To Know About WebLogic
The Top 10 Things Oracle UCM Users Need To Know About WebLogicBrian Huff
 
Web development concepts using microsoft technologies
Web development concepts using microsoft technologiesWeb development concepts using microsoft technologies
Web development concepts using microsoft technologiesHosam Kamel
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula Sorin Chiprian
 

Similar to Play Framework: The Basics (20)

Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
 
eXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework IntroductioneXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework Introduction
 
Rahul Resume.doc
Rahul Resume.docRahul Resume.doc
Rahul Resume.doc
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
Java EE 7 introduction
Java EE 7  introductionJava EE 7  introduction
Java EE 7 introduction
 
Java ee introduction
Java ee introductionJava ee introduction
Java ee introduction
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundry
 
Project report for final year project
Project report for final year projectProject report for final year project
Project report for final year project
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
 
The Play Framework at LinkedIn
The Play Framework at LinkedInThe Play Framework at LinkedIn
The Play Framework at LinkedIn
 
The Play Framework at LinkedIn: productivity and performance at scale - Jim B...
The Play Framework at LinkedIn: productivity and performance at scale - Jim B...The Play Framework at LinkedIn: productivity and performance at scale - Jim B...
The Play Framework at LinkedIn: productivity and performance at scale - Jim B...
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
The Top 10 Things Oracle UCM Users Need To Know About WebLogic
The Top 10 Things Oracle UCM Users Need To Know About WebLogicThe Top 10 Things Oracle UCM Users Need To Know About WebLogic
The Top 10 Things Oracle UCM Users Need To Know About WebLogic
 
Web development concepts using microsoft technologies
Web development concepts using microsoft technologiesWeb development concepts using microsoft technologies
Web development concepts using microsoft technologies
 
Asp.net
Asp.netAsp.net
Asp.net
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula
 
Philly Tech Fest Iis
Philly Tech Fest IisPhilly Tech Fest Iis
Philly Tech Fest Iis
 

More from Philip Langer

Tailor made model comparison: How to customize EMF Compare for your modeling ...
Tailor made model comparison: How to customize EMF Compare for your modeling ...Tailor made model comparison: How to customize EMF Compare for your modeling ...
Tailor made model comparison: How to customize EMF Compare for your modeling ...Philip Langer
 
What every Eclipse developer should know about EMF
What every Eclipse developer should know about EMFWhat every Eclipse developer should know about EMF
What every Eclipse developer should know about EMFPhilip Langer
 
A Brief Introduction to Working with Git
A Brief Introduction to Working with GitA Brief Introduction to Working with Git
A Brief Introduction to Working with GitPhilip Langer
 
You need to extend your models? EMF Facet vs. EMF Profiles
You need to extend your models? EMF Facet vs. EMF ProfilesYou need to extend your models? EMF Facet vs. EMF Profiles
You need to extend your models? EMF Facet vs. EMF ProfilesPhilip Langer
 
Adaptable Model Versioning using Model Transformation By Demonstration
Adaptable Model Versioning using Model Transformation By DemonstrationAdaptable Model Versioning using Model Transformation By Demonstration
Adaptable Model Versioning using Model Transformation By DemonstrationPhilip Langer
 
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)Philip Langer
 
Colex: A Web-based Collaborative Conflict Lexicon
Colex: A Web-based Collaborative Conflict LexiconColex: A Web-based Collaborative Conflict Lexicon
Colex: A Web-based Collaborative Conflict LexiconPhilip Langer
 

More from Philip Langer (7)

Tailor made model comparison: How to customize EMF Compare for your modeling ...
Tailor made model comparison: How to customize EMF Compare for your modeling ...Tailor made model comparison: How to customize EMF Compare for your modeling ...
Tailor made model comparison: How to customize EMF Compare for your modeling ...
 
What every Eclipse developer should know about EMF
What every Eclipse developer should know about EMFWhat every Eclipse developer should know about EMF
What every Eclipse developer should know about EMF
 
A Brief Introduction to Working with Git
A Brief Introduction to Working with GitA Brief Introduction to Working with Git
A Brief Introduction to Working with Git
 
You need to extend your models? EMF Facet vs. EMF Profiles
You need to extend your models? EMF Facet vs. EMF ProfilesYou need to extend your models? EMF Facet vs. EMF Profiles
You need to extend your models? EMF Facet vs. EMF Profiles
 
Adaptable Model Versioning using Model Transformation By Demonstration
Adaptable Model Versioning using Model Transformation By DemonstrationAdaptable Model Versioning using Model Transformation By Demonstration
Adaptable Model Versioning using Model Transformation By Demonstration
 
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
 
Colex: A Web-based Collaborative Conflict Lexicon
Colex: A Web-based Collaborative Conflict LexiconColex: A Web-based Collaborative Conflict Lexicon
Colex: A Web-based Collaborative Conflict Lexicon
 

Recently uploaded

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Call Girls in Naraina Delhi đŸ’¯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi đŸ’¯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi đŸ’¯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi đŸ’¯Call Us 🔝8264348440🔝soniya singh
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...gurkirankumar98700
 

Recently uploaded (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Call Girls in Naraina Delhi đŸ’¯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi đŸ’¯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi đŸ’¯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi đŸ’¯Call Us 🔝8264348440🔝
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
 

Play Framework: The Basics

  • 1. Business Informatics Group Institute of Software Technology and Interactive Systems Vienna University of Technology Favoritenstraße 9-11/188-3, 1040 Vienna, Austria phone: +43 (1) 58801-18804 (secretary), fax: +43 (1) 58801-18896 office@big.tuwien.ac.at, www.big.tuwien.ac.at Play Framework: The Basics Building scalable web applications based on a non-blocking, stateless architecture and the Java Persistence API Philip Langer
  • 2. Outline 1. Motivation and overview 2. Setup and project structure 3. Controllers and routing 4. Templates with Scala 5. Models and JPA 6. Forms and server-side validation 7. Internationalization 8. Authentication 9. Client state on the server 10.Asynchronous results
  • 3. Motivation and Overview 3 ī‚§ Goals of the Play framework ī‚§ Stateless web framework ī‚§ As opposed to stateful ī‚§ Based on an “evented” web server architecture ī‚§ As opposed to threaded ī‚§ Full-stack web framework ī‚§ Including model persistence, template mechanism (view), controller, and testing ī‚§ Aims at being ī‚§ “developer-friendly” (e.g., hot reload mimicking interpreted languages) ī‚§ fully compiled and type safe (even templates and routes) ī‚§ Further nice features ī‚§ RESTful by default ī‚§ Integration of JSON ī‚§ Integration of compilers for CoffeeScript, LESS, etc. ī‚§ Support for long-living connections (WebSocket, Comet, â€Ļ) ī‚§ â€Ļ
  • 4. Motivation and Overview 4 ī‚§ Stateful versus stateless web frameworks ī‚§ Traditional web frameworks are stateful Server-side state is stored for each client in a session Web Server DB
  • 5. Motivation and Overview 5 ī‚§ Stateful versus stateless web frameworks ī‚§ Traditional web frameworks are stateful Server-side state is stored for each client in a session Web Server DB
  • 6. Motivation and Overview 6 ī‚§ Stateful versus stateless web frameworks ī‚§ Traditional web frameworks are stateful Server-side state is stored for each client in a session Load Balancer Web Server Web Server DB Web Server ?
  • 7. Motivation and Overview 7 ī‚§ Stateful versus stateless web frameworks ī‚§ Traditional web frameworks are stateful Server-side state is stored for each client in a session Load Balancer Web Server Web Server DB Web Server
  • 8. DB Motivation and Overview 8 ī‚§ Stateful versus stateless web frameworks ī‚§ Recently stateless web frameworks gained popularity ī‚§ Web server instances do not store user state (“shared nothing”) ī‚§ Stateful client & shared cache (memcached, MongoDB, â€Ļ) ī‚§ Allows to do horizontal scaling (adding/removing web server instances) Load Balancer Web Server Web Server Web Server DB
  • 9. DB Motivation and Overview 9 ī‚§ Threaded versus evented web servers ī‚§ Thread pool maintains a number of threads ī‚§ For each request, a thread is allocated until the request is completed Load Balancer Web Server Web Server Web Server Web Server Web Server Web Server Web Server Web Server
  • 10. DB Motivation and Overview 10 ī‚§ Threaded versus evented web servers ī‚§ Thread pool maintains a number of threads ī‚§ For each request, a thread is allocated until the request is completed ī‚§ Thread is occupied but potentially idle due to long-running requests to other services Load Balancer Web Server Web Server Web Server Web Server Web Server Web Server Web Server Web Server public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { StockService s1 = new StockService(); PricingService s2 = new PricingService(); List<Stock> stocks = s1.requestStocks(); List<Price> prices = new ArrayList<long>(); for (Stock stock : stocks) { long price = s2.getPrice(stock.getId()); prices.add(price); } // ... renderResponse(response, prices); }
  • 11. DB Motivation and Overview 11 ī‚§ Threaded versus evented web servers ī‚§ Thread pool maintains a number of threads ī‚§ For each request, a thread is allocated until the request is completed ī‚§ Thread is occupied but potentially idle due to long-running requests to other services Load Balancer Web Server Web Server Web Server Web Server Web Server Web Server Web Server Web Server When latency goes up here, threads are all occupied soon īƒ  new requests are queued.
  • 12. DB Motivation and Overview 12 ī‚§ Threaded versus evented web servers ī‚§ Thread pool maintains a number of threads ī‚§ For each request, a thread is allocated until the request is completed ī‚§ Thread is occupied but potentially idle due to long-running requests to other services Load Balancer Web Server Web Server Web Server Web Server Web Server Web Server Web Server Web Server Latency goes up here too, threads get all occupied īƒ  new requests are queued too.
  • 13. DB Motivation and Overview 13 ī‚§ Threaded versus evented web servers ī‚§ Thread pool maintains a number of threads ī‚§ For each request, a thread is allocated until the request is completed ī‚§ Thread is occupied but potentially idle due to long-running requests to other services Load Balancer Web Server Web Server Web Server Web Server Web Server Web Server Web Server Web Server same hereâ€Ļ and hereâ€Ļ and hereâ€Ļ and hereâ€Ļ and hereâ€Ļ
  • 14. Motivation and Overview 14 ī‚§ Threaded versus evented web servers ī‚§ Play is based on Netty An event-driven client-server framework ī‚§ Play is based on Akka and the Promise/Future API Software library for building concurrent applications ī‚§ For each CPU core, there is one thread/process ī‚§ Enables asynchronous, non-blocking server requests/responses īƒ  Thread is occupied only, if there is something to do īƒ  No sensitivity to downstream latency
  • 15. Motivation and Overview 15 ī‚§ Full-stack framework ī‚§ Model-view-controller architecture ī‚§ Model and controller can be realized with Java or Scala ī‚§ View is realized with a template syntax and Scala ī‚§ Model persistence is based on Ebean by default ī‚§ But any other persistence mechanism can be used too ī‚§ We will use the Java Persistence API instead ī‚§ Play integrates unit, integration, and system testing tools ī‚§ JUnit ī‚§ Dedicated APIs to call controllers and views ī‚§ Selenium WebDriver and FluentLenium
  • 16. Motivation and Overview 16 ī‚§ Developer friendliness ī‚§ Aims at combining the benefits of ī‚§ Frameworks using interpreted languages (no compile/deploy/test delay) ī‚§ Type safety and checks of compiled languages ī‚§ Hot reload ī‚§ Framework listens for changes and compiles & deploys in background ī‚§ Change something, hit refresh in the browser, and you will see the effect ī‚§ Compiled, static-typed language is used ī‚§ Java or Scala ī‚§ Also templates and routes are type checked
  • 17. Setup and project structure 17 Create a new play project $ play new ewa-play-intro _ _ __ | | __ _ _ _ | '_ | |/ _' | || | | __/|_|____|__ / |_| |__/ play 2.2.1 built with Scala 2.10.2 (running Java 1.7.0_25), http://www.playframework.com The new application will be created in /home/whatever/ewa-play-intro What is the application name? [ewa-play-intro] Which template do you want to use for this new application? 1 - Create a simple Scala application 2 - Create a simple Java application > 2 OK, application ewa-play-intro is created. Have fun! https://github.com/planger/ewa-play-intro/tree/a616c8b
  • 18. Setup and project structure 18 The play console Open the project folder (i.e., ewa-play-intro) in a console and start play $ play â€Ļ [ewa-play-intro] $ help play These commands are available: ----------------------------- classpath Display the project classpath. clean Clean all generated files. compile Compile the current application. console Launch the interactive Scala console (use :quit to exit). dependencies Display the dependencies summary. dist Construct standalone application package. exit Exit the console. h2-browser Launch the H2 Web browser. license Display licensing informations. package Package your application as a JAR. play-version Display the Play version. publish Publish your application in a remote repository. publish-local Publish your application in the local repository. reload Reload the current application build file. run <port> Run the current application in DEV mode. test Run Junit tests and/or Specs from the command line eclipse generate eclipse project file idea generate Intellij IDEA project file sh <command to run> execute a shell command start <port> Start the current application in another JVM in PROD mode. update Update application dependencies. https://github.com/planger/ewa-play-intro/tree/a616c8b
  • 19. Setup and project structure 19 Setup the IDE (Eclipse or IntelliJ) // you can also use any editor you like (compiling is done by Play) [ewa-play-intro] $ eclipse [info] About to create Eclipse project files for your project(s). [info] Successfully created Eclipse project files for project(s): [info] ewa-play-intro In Eclipse Import īƒ  Existing Projects into Workspace īƒ  Select https://github.com/planger/ewa-play-intro/tree/a616c8b
  • 20. Setup and project structure 20 Project structure ī‚§ app/ contains the application’s core in models, controllers, and views directories. ī‚§ conf/ contains all the application’s configuration files, especially the application.conf file, the routes definition files, and the messages files used for internationalization. ī‚§ project/ contains the build scripts. ī‚§ public/ contains all the publicly available resources: JavaScript, stylesheets, and images. ī‚§ test/ contains all the application’s tests. https://github.com/planger/ewa-play-intro/tree/a616c8b
  • 21. Setup and project structure 21 Run the application [ewa-play-intro] $ run [info] Updating {file:/home/whatever/ewa-play-intro/}ewa-play-intro... [info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin[info] Resolving org.fusesource.jansi#jansi;1.4 ... [info] Done updating. --- (Running the application from SBT, auto-reloading is enabled) --- [info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000 (Server started, use Ctrl+D to stop and go back to the console...) https://github.com/planger/ewa-play-intro/tree/a616c8b
  • 22. Setup and project structure 22 Run the application [ewa-play-intro] $ run [info] Updating {file:/home/whatever/ewa-play-intro/}ewa-play-intro... [info] Resolving org.hibernate.javax.persistence#hibernate-jpa-2.0-api;1.0.1.Fin[info] Resolving org.fusesource.jansi#jansi;1.4 ... [info] Done updating. --- (Running the application from SBT, auto-reloading is enabled) --- [info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000 (Server started, use Ctrl+D to stop and go back to the console...) https://github.com/planger/ewa-play-intro/tree/a616c8b
  • 23. Controllers and Routing 23 ī‚§ Controller are static classes ī‚§ Located in app/controllers ī‚§ Inherit from an abstract Controller class ī‚§ Access to methods for obtaining request and sending back requests ī‚§ request().remoteAddress() īƒ  Access Request object and obtains address ī‚§ ok("Hello") īƒ  Result “x” with HTTP status 200 ī‚§ Public static methods are also called “actions” ī‚§ Take arbitrary parameters ī‚§ Return Result object public static Result sayHello() { return ok("Hello " + request().remoteAddress()); } public static Result sayHelloTo(String name) { if (name.toLowerCase().matches("[a-z]")) { String theName = name.toUpperCase(); return ok("Hello " + theName); } else { return badRequest("Provide a proper name!"); } } http://www.playframework.com/documentation/2.0/JavaActions https://github.com/planger/ewa-play-intro/tree/ef1891c
  • 24. Controllers and Routing 24 ī‚§ Routing maps incoming requests to controller actions ī‚§ Syntax: <HTTPMethod> <URIPattern> <ControllerAction> ī‚§ HTTPMethod: GET, POST, DELETE, â€Ļ ī‚§ Configured in conf/routes ī‚§ Routes are compiled and type safe too! ī‚§ URI patterns support ī‚§ Variable extraction (:name) ī‚§ Dynamic parts spanning several / (path*) ī‚§ Regular expressions ($name<[a-z]>) ī‚§ Controller actions support default values # in conf/routes GET /anonymoushello controllers.Application.sayHello() GET /hello controllers.Application.sayHelloTo(name: String = "Stranger") GET /hello/:name controllers.Application.sayHelloTo(name: String) http://www.playframework.com/documentation/2.0/JavaRouting https://github.com/planger/ewa-play-intro/tree/ef1891c
  • 25. Templates with Scala 25 ī‚§ Templates ī‚§ Located in app/views/ ī‚§ Named *.scala.<format> ī‚§ Templates are compiled and are type-checked ī‚§ Example: app/views/index.scala.html īƒ  class named views.html.index To render a template from within a controller: â€Ļ import views.html.*; â€Ļ public static Result index() { return ok(index.render("Your new application is ready.")); } https://github.com/planger/ewa-play-intro/tree/ef1891c
  • 26. Templates with Scala 26 ī‚§ Templates ī‚§ They are basically Scala functions ī‚§ They may take parameters ī‚§ They may call other functions ī‚§ Static content mixed with Scala code using @ In main.scala.html @(title: String)(content: Html) <!DOCTYPE html> <html> <head> <title>@title</title> <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")"> </head> <body> @content </body> </html> http://www.playframework.com/documentation/2.0/JavaTemplates https://github.com/planger/ewa-play-intro/tree/ef1891c
  • 27. Templates with Scala 27 ī‚§ Templates ī‚§ They are basically Scala functions ī‚§ They may take parameters ī‚§ They may call other functions ī‚§ Static content mixed with Scala code using @ In main.scala.html @(title: String)(content: Html) <!DOCTYPE html> <html> <head> <title>@title</title> <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")"> </head> <body> @content </body> </html> http://www.playframework.com/documentation/2.0/JavaTemplates Reverse routing GET /assets/*file controllers.Assets.at(path="/public", file) https://github.com/planger/ewa-play-intro/tree/ef1891c
  • 28. Templates with Scala 28 ī‚§ Templates ī‚§ They are basically Scala functions ī‚§ They may take parameters ī‚§ They may call other functions ī‚§ Static content mixed with Scala code using @ In main.scala.html @(title: String)(content: Html) <!DOCTYPE html> â€Ļ @content â€Ļ In another.scala.html @(message: String) @main("This is the title of type String") { <h1>This is the content of type Html</h1> <p>@message</p> } http://www.playframework.com/documentation/2.0/JavaTemplates https://github.com/planger/ewa-play-intro/tree/ef1891c
  • 29. Templates with Scala 29 ī‚§ Example app/controllers/Application.java public static Result listCharacters(String text) { List<Character> characters = new ArrayList<Character>(); for (char c : text.toLowerCase().toCharArray()) if (!characters.contains(c)) characters.add(c); return ok(characterlist.render(text, characters)); } app/views/characterlist.scala.html @(text: String, characters: List[Character]) <!DOCTYPE html> <html> <head> <title>@text</title> </head> <body> <h1>Characters of @text</h1> @charactersAsUnorderedList(characters) </body> </html> @charactersAsUnorderedList(characters: List[Character]) = { @if(!characters.isEmpty()) { <ul> @for(character <- characters) { <li>@character</li> } </ul> } } https://github.com/planger/ewa-play-intro/tree/c1b1594
  • 30. Models and JPA 30 ī‚§ Models ī‚§ Java or Scala classes that should be located in app/models/ ī‚§ Represent the domain model (cf. MVC pattern) ī‚§ Basically, they are plain old Java objects ī‚§ Nothing special to be considered for working with them in Play ī‚§ Model objects are usually persisted in a database ī‚§ Play integrates Ebean1 by default (ORM persistence layer) ī‚§ But any other persistence layer may be used instead ī‚§ In this lecture, we use JPA2 & Hibernate3 īƒ  A brief excursus on object/relational mapping (ORM), JPA, and Hibernate 1 http://www.avaje.org/ 2 http://www.oracle.com/technetwork/java/javaee/tech/persistence-jsp-140049.html 3 http://hibernate.org/orm/
  • 31. JPA: Java Persistence API 31 ī‚§ API for managing the persistence of a Java domain model ī‚§ Object/relational mapping ī‚§ Java objects are persisted in a relational database ī‚§ Standardized under the Java Community Process Program ī‚§ Annotations for specifying persistent entities ī‚§ Object/relational mapping metadata ī‚§ API for storing, querying, and deleting objects ī‚§ Java Persistence Query Language (JPQL) ī‚§ Several JPA providers available ī‚§ Hibernate ī‚§ EclipseLink ī‚§ Apache OpenJPA
  • 32. JPA: Persistent Entities 32 ī‚§ Annotated Plain Old Java Objects ī‚§ Lightweight persistent domain object ī‚§ Persistent identity field ī‚§ Typically EJB style classes ī‚§ Public or protected no-arg constructor ī‚§ Getters and setters ī‚§ Support for ī‚§ Abstract classes and inheritance ī‚§ Relationships (OneToOne, OneToMany, ManyToMany) ī‚§ Each entity is typically represented by one table ī‚§ Each instance of an entity corresponds to a row in that table ī‚§ Entities may have both persistent and non-persistent state ī‚§ Persistent simple or complex typed data ī‚§ Non-persistent state (transient)
  • 33. JPA: Persistent Entity 33 ī‚§ Example @Entity @Access(AccessType.FIELD) public class Employee { @Id private long id; private String name; @Transient private Money salary; @ManyToOne(fetch=FetchType.LAZY) private Employee manager; @Access(AccessType.PROPERTY) private BigDecimal getSalary() { return this.salary.toNumber(); } private void setSalary(BigDecimal salary) { this.salary = new Money(salary); } } EMPLOYEE ID NAME MANAGER_ID SALARY
  • 34. Models and JPA 34 ī‚§ Integrating Play with JPA and Hibernate ī‚§ Add dependencies (JPA and hibernate) to build.sbt ī‚§ Expose the datasource through JNDI in conf/application.conf ī‚§ Add persistence.xml to conf/META-INF ī‚§ Add dependency to Eclipse project (just for IDE support) ī‚§ Project Preferences īƒ  Java Build Path īƒ  Add External Library ī‚§ Browse to your Play local installation and select play-2.2.1/repository/local/com.typesafe.play/play-java-jpa_2.10/2.2.1/jars/play-java-jpa_2.10.jar ī‚§ Reload dependencies in the Play console $ play reload http://www.playframework.com/documentation/2.2.x/JavaJPA https://github.com/planger/ewa-play-intro/tree/15c5b4a
  • 35. Models and JPA 35 ī‚§ Using JPA in Play ī‚§ Model class with JPA annotations (javax.persistence.*) @Entity public class Pet { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Gender gender; â€Ļ // getters and setters ī‚§ Controllers may access the JPA entity manager ī‚§ Actions have to be annotated with javax.persistence.Transactional @Transactional public static Result list() { Collection<Pet> pets = getAllPets(); return ok(Json.toJson(pets)); } private static Collection<Pet> getAllPets() { EntityManager em = play.db.jpa.JPA.em(); String queryString = "SELECT p FROM Pet p"; TypedQuery<Pet> query = em.createQuery(queryString, Pet.class); return (Collection<Pet>) query.getResultList(); } http://www.playframework.com/documentation/2.2.x/JavaJPA https://github.com/planger/ewa-play-intro/tree/d870e86
  • 36. Forms and server-side validation 36 ī‚§ Creating and processing dynamic forms ī‚§ Helpers to create HTML forms in templates @helper.form(action = routes.Pets.createPetResponse) { <select name="petId"> @for(pet <- pets) { <option value="@pet.getId()">@pet.getName()</option> } </select> <input type="text" id="petResponse" name="petResponse" /> <button type="submit" name="action" value="new">Respond</button> } ī‚§ Helpers to handle HTTP form data in controllers @Transactional public static Result createPetResponse() { DynamicForm form = Form.form().bindFromRequest(); String petId = form.data().get("petId"); String petResponse = form.data().get("petResponse"); Pet pet = getPetById(Long.valueOf(petId)); return ok(pet.getName() + " says " + petResponse); } http://www.playframework.com/documentation/2.0/ScalaFormHelpers http://www.playframework.com/documentation/2.0/JavaForms https://github.com/planger/ewa-play-intro/tree/75fb91d
  • 37. Forms and server-side validation 37 ī‚§ Creating and processing forms for model classes ī‚§ Helpers to create HTML forms in templates <h1>New pet</h1> @helper.form(action = routes.Pets.createPet) { @helper.inputText(form("name")) @helper.inputRadioGroup( form("gender"), options = Seq(("male"->"Male"), ("female"->"Female"))) <button type="submit" name="action" value="new">Save</button> } ī‚§ Helpers to handle HTTP form data in controllers @Transactional public static Result createPet() { Form<Pet> form = Form.form(Pet.class).bindFromRequest(); if (form.hasErrors()) { return badRequest(petform.render(form)); } else { Pet pet = form.get(); JPA.em().persist(pet); return redirect(routes.Pets.list()); } } http://www.playframework.com/documentation/2.0/ScalaFormHelpers http://www.playframework.com/documentation/2.0/JavaForms https://github.com/planger/ewa-play-intro/tree/75fb91d
  • 38. Forms and server-side validation 38 ī‚§ Creating and processing forms for model classes ī‚§ Helpers to create HTML forms in templates <h1>New pet</h1> @helper.form(action = routes.Pets.createPet) { @helper.inputText(form("name")) @helper.inputRadioGroup( form("gender"), options = Seq(("male"->"Male"), ("female"->"Female"))) <button type="submit" name="action" value="new">Save</button> } ī‚§ Helpers to handle HTTP form data in controllers @Transactional public static Result createPet() { Form<Pet> form = Form.form(Pet.class).bindFromRequest(); if (form.hasErrors()) { return badRequest(petform.render(form)); } else { Pet pet = form.get(); JPA.em().persist(pet); return redirect(routes.Pets.list()); } } http://www.playframework.com/documentation/2.0/ScalaFormHelpers http://www.playframework.com/documentation/2.0/JavaForms <form action="/pets" method="POST"> <dl class=" " id="name_field"> <dt><label for="name">name</label></dt> <dd> <input type="text" id="name" name="name" value="" > </dd> </dl> <dl class=" " id="gender_field"> <dt><label for="gender">gender</label></dt> <dd> <span class="buttonset" id="gender"> <input type="radio" id="gender_male" name="gender" value="male" > <label for="gender_male">Male</label> <input type="radio" id="gender_female" name="gender" value="female" > <label for="gender_female">Female</label> </span> </dd> </dl> <button type="submit" name="action" value="new">Save</button> </form> https://github.com/planger/ewa-play-intro/tree/75fb91d
  • 39. Forms and server-side validation 39 ī‚§ Server-side validation of model classes ī‚§ Several validation rules available in play.data.validation.Constraints public class Pet { â€Ļ @Constraints.Required @Constraints.MinLength(4) @Constraints.MaxLength(8) private String name; â€Ļ ī‚§ Custom validation rules can be specified in a validate method public List<ValidationError> validate() { List<ValidationError> errors = null; if (!Character.isUpperCase(name.charAt(0))) { errors = new ArrayList<ValidationError>(); errors.add(new ValidationError("name", "Must start with upper case letter")); } return errors; } http://www.playframework.com/documentation/2.0/JavaForms https://github.com/planger/ewa-play-intro/tree/9716829
  • 40. Forms and server-side validation 40 ī‚§ Displaying validation error messages ī‚§ Redirect back to form in case of an error if (form.hasErrors()) { return badRequest(petform.render(form)); } ī‚§ Validation errors are available in forms for custom messages @for(error <- form("name").errors) { <div id="error_msg_name" class="error" role="alert"> @error.message </div> } ī‚§ When using form helpers, error messages are rendered automatically http://www.playframework.com/documentation/2.0/JavaForms https://github.com/planger/ewa-play-intro/tree/9716829
  • 41. Internationalization 41 ī‚§ Specifying supported languages ī‚§ In conf/application.conf application.langs=en,de ī‚§ Externalizing messages ī‚§ In conf/messages.<langcode> pet.gender=Geschlecht pet.response={0} sagt {1}. ī‚§ Using messages in templates <div>@Messages("pet.gender")</div> <div>@Messages("pet.response", pet.getName(), petResponse)</div> ī‚§ Using messages in Java using play.api.i18n.Messages Messages.get("pet.gender") Messages.get("pet.response", pet.getName(), petResponse) http://www.playframework.com/documentation/2.0/JavaI18N https://github.com/planger/ewa-play-intro/tree/d1bf60b
  • 42. Authentication 42 ī‚§ Authentication is realized using action composition ī‚§ Action composition enables to process actions in a chain ī‚§ Each action can modify the request before passing it on ī‚§ It may also decide to not pass the request (e.g., if not authenticated) ī‚§ Play already provides a built-in authenticator action ī‚§ Subclass play.mvc.Security.Authenticator ī‚§ getUsername(Http.Context ctx) ī‚§ Return null if not authenticated ī‚§ onUnauthorized(Http.Context ctx) ī‚§ Decide what to do if unauthorized ī‚§ Annotate entire controllers or single controller methods (actions) @Security.Authenticated(<yoursubclass>.class) public static Result createPet() {â€Ļ} https://www.playframework.com/documentation/2.2.x/JavaGuide4
  • 43. Client state on the server 43 ī‚§ Web server is stateless ī‚§ Sometimes we need to save client state ī‚§ E.g., to store whether a user is logged in already, shopping cart etc. ī‚§ Options to store a client state ī‚§ Session ī‚§ Stored in a cookie at the client ī‚§ Limited to 4 KB ī‚§ Hashed and encrypted (to prohibit manipulation) ī‚§ In a controller: session("key", "value"); session().remove("key"); ī‚§ Cache ī‚§ Enables caching of objects and even entire HTTP responses ī‚§ Should not be used to store irreproducible data (well, it‘s a cache) ī‚§ In a controller: Cache.set("key", "value"); Cache.get("key"); ī‚§ Datastore ī‚§ Larger irreproducible data should be stored in a database https://www.playframework.com/documentation/2.2.x/JavaSessionFlash https://www.playframework.com/documentation/2.2.x/JavaCache
  • 44. Asynchronous results 44 ī‚§ Useful for longer running controller actions ī‚§ E.g., when calling other web services or long-running database queries ī‚§ Avoids blocking a thread ī‚§ Play provides Scala‘s Promise API and asynchronous results ī‚§ A promise is a wrapper of a future value ī‚§ A Promise<T> will eventually yield the value T (or an error) ī‚§ For an asynchronous result, return a Promise<Result> ī‚§ Once the Promise<Result> yields the actual data the result is sent to the client public static Promise<Result> longRunningAction() { Logger.info("Long running action entry"); WSRequestHolder duckduck = WS.url("https://www.duckduckgo.com"); Promise<Response> duckduckResponse = duckduck.get(); Promise<Result> result = duckduckResponse.map(toResult); Logger.info("Long running action exit"); return result; } private static Function<Response, Result> toResult = new Function<Response, Result>() { public Result apply(Response response) { Logger.info("Inside the toResult function"); return ok(response.getBody()).as("text/html"); } }; http://www.playframework.com/documentation/2.0/ScalaFormHelpers http://www.playframework.com/documentation/2.0/JavaForms https://github.com/planger/ewa-play-intro/tree/706f06e
  • 45. References 45 ī‚§ Code of these slides is available at github ī‚§ https://github.com/planger/ewa-play-intro ī‚§ Official documentation and tutorials ī‚§ http://www.playframework.com/documentation/2.2.x/JavaHome ī‚§ Parts of these slides are based on slides by Yevgeniy Brikman ī‚§ http://www.slideshare.net/brikis98/play-framework-async-io-with-java-and-scala ī‚§ https://www.youtube.com/watch?v=8z3h4Uv9YbE ī‚§ Another nice tutorial on Play ī‚§ https://www.youtube.com/watch?v=9_YYgl65FLs