SlideShare a Scribd company logo
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
Play 2.0
● Java and Scala source code goes here.

● Can create own packages
Play 2.0
Play 2.0
Play 2.0
Play 2.0
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

More Related Content

Play 2.0