SlideShare ist ein Scribd-Unternehmen logo
1 von 68
Play Framework
2.1
Overview
Differences from 1.0
Overview
●   Stateless web framework
●   RESTful-friendly
●   Asynchronous ability built in
●   LESS and CoffeeScript friendly too!
Differences from 1.0
Template engine
1.0               2.0

Groovy Pages      Scala Templates
Persistence
1.0           2.0

Hibernate     Ebean and Hibernate
Language Support
1.0                2.0

Java               Java and Scala
Dynamic compilation
1.0                   2.0

Byte code injection   Dynamic compilation
                      via SBT
And more...
Reports on errors in JavaScript
Designed for concurrent, long connections
CRSF protection
Modules
jdbc
anorm
javaCore
javaJdbc
javaEbean
javaJpa
filters
Setup
Using Play from the console
Enter an existing Play application directory and
type 'play'
Using play in your IDE
http://www.playframework.com/documentation/2.1.0/IDE
Creating an application
play new your_app_name
Example Time
● Java and Scala source code goes here.

● Can create own packages
Let's create a Play application...
Templates
Declared at the top of the file


@(customer: models.Customer, orders: List
[models.Order])
Are iterable...

<ul>
@for(p <- products) {
  <li>@p.getName() ($@p.getPrice())</li>
}
</ul>
Are conditional...

@if(items.isEmpty()) {
  <h1>Nothing to display</h1>
} else {
  <h1>@items.size() items!</h1>
}
Can be reusable...

@display(product: models.Product) = {
  @product.getName() ($@product.getPrice())
}

<ul>
@for(product <- products) {
  @display(product)
}
</ul>
or
@title(text: String) = @{
  text.split(' ').map(_.capitalize).mkString(" ")
}

<h1>@title("hello world")</h1>
Ability for server side comments

@*********************
* This is a comment *
*********************@
Back to the example...
HTML Forms
HTML form submission data is easy to deal
with using the play.data.* package

Uses Spring data binder to wrap a model
(class)
To use:
public class User {
  public String email;
  public String password;
}

Form<User> userForm = form(User.class);
Now, you can create a User from a
hashmap or request object

Map<String,String> anyData = new HashMap();
anyData.put("email", "bob@gmail.com");
anyData.put("password", "secret");

User user = userForm.bind(anyData).get();


or

User user = userForm.bindFromRequest().get();
Can add constraints using JSR303
implementation
public class User {

    @Required
    public String email;
    public String password;

    public String validate() {
      if(authenticate(email,password) == null) {
          return "Invalid email or password";
      }
      return null;
    }
}
Custom handling of errors when
invalid form submissions

if(userForm.hasErrors()) {
    return badRequest(form.render(userForm));
} else {
    User user = userForm.get();
    return ok("Got user " + user);
}
FormHelpers
HTML Form creation is simple

@helper.form(action = routes.Application.submit()) {

}
Can add parameters too

@helper.form(action = routes.Application.submit(),
'id -> "myForm") {

}
There are special FormHelpers

@(myForm: Form[User])

@helper.form(action = routes.Application.submit()) {

  @helper.inputText(myForm("username"), 'id -> "username", 'size
-> 30)

    @helper.inputPassword(myForm("password"))

}
Bad news: the markup isn't that pretty.

Good news: you can take control
Back to the example...
Databases
By convention, the default database must be
called default.

Other databases can have custom names.

Only the h2 database driver is provided by
default. You'll have to manually configure any
other drivers as an application dependency.
EBean and Hibernate
Both Ebean and Hibernate are supported

Ebean is natively supported
Hibernate as an application dependency
Ebean
Enabled in the conf/application.conf file

***Play generates getter/setters to be available
at runtime, not compile time!***
Hibernate
Add Hibernate as a dependency

val appDependencies = Seq(
  "org.hibernate" % "hibernate-entitymanager" %
"3.6.9.Final"
)
Create a persistence.xml in conf/META-
INF
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
         version="2.0">

  <persistence-unit name="defaultPersistenceUnit" transaction-type="
RESOURCE_LOCAL">
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
     <non-jta-data-source>DefaultDS</non-jta-data-source>
     <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.
H2Dialect"/>
     </properties>
  </persistence-unit>
</persistence>
Must manually denote a transaction
using @Transactional

@Transactional
public static Result index() {
  ...
}
Can retrieve current entity manager
using the play.db.jpa.JPA helper
class

public static Company findById(Long id) {
  return JPA.em().find(Company.class, id);
}
Working with JSON
JSON Request
Content-Type must specify text/json or
application/json MIME type
import org.codehaus.jackson.JsonNode;
import play.mvc.BodyParser;
...

@BodyParser.Of(BodyParser.Json.class)
public static Result sayHello() {
 JsonNode json = request().body().asJson();
 String name = json.findPath("name").getTextValue();

    if(name == null) {
      return badRequest("Missing parameter [name]");
    } else {
      return ok("Hello " + name);
    }
}
Returning a result of JSON is easy too.
import play.libs.Json;
import org.codehaus.jackson.node.ObjectNode;
...

@BodyParser.Of(BodyParser.Json.class)
public static Result sayHello() {
  JsonNode json = request().body().asJson();
  ObjectNode result = Json.newObject();
  String name = json.findPath("name").getTextValue();
  if(name == null) {
    result.put("status", "KO");
    result.put("message", "Missing parameter [name]");
    return badRequest(result);
  } else {
    result.put("status", "OK");
    result.put("message", "Hello " + name);
    return ok(result);
  }
}
Handling XML requests and responses is easy
too.
build/deploy
sbt
Scala DSL
Uses build definition
Accurate incremental recompilation
Not all sbt features are included in Play
sbt build definition
Use := to set a setting

There are a number of default settings.
● Resovers
● Source
● Target
● Hooks for CoffeeScript, LESS, and
  JavaScript minification and generation
Dependency Management with Ivy
via sbt
Add dependencies in Build.scala

Syntax:

val appDependencies = Seq(
  "org.apache.derby" % "derby" % "10.4.1.3"
)
Resolvers
Uses Maven2 and Scala Tools by default

You can add your own:
resolvers += (
   "Local Repository" at "file://"+Path.userHome.
absolutePath+"/.m2/repository"
)
Authentication and Authorization
● Play has its own authorization and
  authentication

● No JAAS compatibility

● Only basic support, may not be enough for
  enterprise apps

● There are a number of third party modules
  that may provide the auth support you need.
Links
API: http://www.playframework.
com/documentation/api/2.1.0/java/index.html

Java documentation: http://www.
playframework.com/documentation/2.1.0/Home
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

OpenStack Keystone with LDAP
OpenStack Keystone with LDAPOpenStack Keystone with LDAP
OpenStack Keystone with LDAP
 
Sq lite presentation
Sq lite presentationSq lite presentation
Sq lite presentation
 
SQLite - Overview
SQLite - OverviewSQLite - Overview
SQLite - Overview
 
ppt
pptppt
ppt
 
SQL on Linux
SQL on LinuxSQL on Linux
SQL on Linux
 
Insight on MongoDB Change Stream - Abhishek.D, Mydbops Team
Insight on MongoDB Change Stream - Abhishek.D, Mydbops TeamInsight on MongoDB Change Stream - Abhishek.D, Mydbops Team
Insight on MongoDB Change Stream - Abhishek.D, Mydbops Team
 
Backup and Restore SQL Server Databases in Microsoft Azure
Backup and Restore SQL Server Databases in Microsoft AzureBackup and Restore SQL Server Databases in Microsoft Azure
Backup and Restore SQL Server Databases in Microsoft Azure
 
MySQL Usability Guidelines
MySQL Usability GuidelinesMySQL Usability Guidelines
MySQL Usability Guidelines
 
Linux17 MySQL_installation
Linux17 MySQL_installationLinux17 MySQL_installation
Linux17 MySQL_installation
 
Tech Ed North America 2014 - Java on Azure
Tech Ed North America 2014 - Java on AzureTech Ed North America 2014 - Java on Azure
Tech Ed North America 2014 - Java on Azure
 
Mongo db world 2014 nyc mongodb on azure - tips tricks and examples
Mongo db world 2014 nyc   mongodb on azure - tips tricks and examplesMongo db world 2014 nyc   mongodb on azure - tips tricks and examples
Mongo db world 2014 nyc mongodb on azure - tips tricks and examples
 
How to backup Oracle Database to Dropbox, Windows Azure, Amazon S3, and local...
How to backup Oracle Database to Dropbox, Windows Azure, Amazon S3, and local...How to backup Oracle Database to Dropbox, Windows Azure, Amazon S3, and local...
How to backup Oracle Database to Dropbox, Windows Azure, Amazon S3, and local...
 
MySQL Guide for Beginners
MySQL Guide for BeginnersMySQL Guide for Beginners
MySQL Guide for Beginners
 
Tech ED 2014 Running Oracle Databases and Application Servers on Azurev1
Tech ED 2014   Running Oracle Databases and Application Servers on Azurev1Tech ED 2014   Running Oracle Databases and Application Servers on Azurev1
Tech ED 2014 Running Oracle Databases and Application Servers on Azurev1
 
Security features In MySQL 8.0
Security features In MySQL 8.0Security features In MySQL 8.0
Security features In MySQL 8.0
 
HandsOn ProxySQL Tutorial - PLSC18
HandsOn ProxySQL Tutorial - PLSC18HandsOn ProxySQL Tutorial - PLSC18
HandsOn ProxySQL Tutorial - PLSC18
 
Getting started into mySQL
Getting started into mySQLGetting started into mySQL
Getting started into mySQL
 
Presentation
PresentationPresentation
Presentation
 
Percona live 2021 Practical Database Automation with Ansible
Percona live 2021 Practical Database Automation with Ansible Percona live 2021 Practical Database Automation with Ansible
Percona live 2021 Practical Database Automation with Ansible
 
MySQL High Availability Deep Dive
MySQL High Availability Deep DiveMySQL High Availability Deep Dive
MySQL High Availability Deep Dive
 

Andere mochten auch

Andere mochten auch (7)

DevsMeetUp Freiburg: Behavior Driven Development with Behat/Mink
DevsMeetUp Freiburg: Behavior Driven Development with Behat/MinkDevsMeetUp Freiburg: Behavior Driven Development with Behat/Mink
DevsMeetUp Freiburg: Behavior Driven Development with Behat/Mink
 
Spock pres
Spock presSpock pres
Spock pres
 
Basic architecuture and operation concept of Backlog and Cacoo
Basic architecuture and operation concept of Backlog and CacooBasic architecuture and operation concept of Backlog and Cacoo
Basic architecuture and operation concept of Backlog and Cacoo
 
MongoDB and hadoop
MongoDB and hadoopMongoDB and hadoop
MongoDB and hadoop
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
2015/11/15 Javaでwebアプリケーション入門
2015/11/15 Javaでwebアプリケーション入門2015/11/15 Javaでwebアプリケーション入門
2015/11/15 Javaでwebアプリケーション入門
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 

Ähnlich wie Play 2.0

Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 

Ähnlich wie Play 2.0 (20)

Hibernate
Hibernate Hibernate
Hibernate
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
 
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala Traits Event , New Delh...
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
 
Web Development Study Jam #2 _ Basic JavaScript.pptx
Web Development Study Jam #2 _ Basic JavaScript.pptxWeb Development Study Jam #2 _ Basic JavaScript.pptx
Web Development Study Jam #2 _ Basic JavaScript.pptx
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Intorduction of Playframework
Intorduction of PlayframeworkIntorduction of Playframework
Intorduction of Playframework
 
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Jetpack, with new features in 2021 GDG Georgetown IO Extended
Jetpack, with new features in 2021 GDG Georgetown IO ExtendedJetpack, with new features in 2021 GDG Georgetown IO Extended
Jetpack, with new features in 2021 GDG Georgetown IO Extended
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Play 2.0