Play Framework2.1
OverviewDifferences from 1.0
Overview
●   Stateless web framework●   RESTful-friendly●   Asynchronous ability built in●   LESS and CoffeeScript friendly too!
Differences from 1.0
Template engine1.0               2.0Groovy Pages      Scala Templates
Persistence1.0           2.0Hibernate     Ebean and Hibernate
Language Support1.0                2.0Java               Java and Scala
Dynamic compilation1.0                   2.0Byte code injection   Dynamic compilation                      via SBT
And more...Reports on errors in JavaScriptDesigned for concurrent, long connectionsCRSF protection
ModulesjdbcanormjavaCorejavaJdbcjavaEbeanjavaJpafilters
Setup
Using Play from the consoleEnter an existing Play application directory andtype play
Using play in your IDEhttp://www.playframework.com/documentation/2.1.0/IDE
Creating an applicationplay new your_app_name
Example Time
● Java and Scala source code goes here.● Can create own packages
Lets 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 <- pro...
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 dealwith using the play.data.* packageUses 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 ahashmap or request objectMap<String,String> anyData = new HashMap();anyData.put("email", ...
Can add constraints using JSR303implementationpublic class User {    @Required    public String email;    public String pa...
Custom handling of errors wheninvalid form submissionsif(userForm.hasErrors()) {    return badRequest(form.render(userForm...
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(...
Bad news: the markup isnt that pretty.Good news: you can take control
Back to the example...
Databases
By convention, the default database must becalled default.Other databases can have custom names.Only the h2 database drive...
EBean and HibernateBoth Ebean and Hibernate are supportedEbean is natively supportedHibernate as an application dependency
EbeanEnabled in the conf/application.conf file***Play generates getter/setters to be availableat runtime, not compile time...
Hibernate
Add Hibernate as a dependencyval 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="ht...
Must manually denote a transactionusing @Transactional@Transactionalpublic static Result index() {  ...}
Can retrieve current entity managerusing the play.db.jpa.JPA helperclasspublic static Company findById(Long id) {  return ...
Working with JSON
JSON RequestContent-Type must specify text/json orapplication/json MIME type
import org.codehaus.jackson.JsonNode;import play.mvc.BodyParser;...@BodyParser.Of(BodyParser.Json.class)public static Resu...
Returning a result of JSON is easy too.import play.libs.Json;import org.codehaus.jackson.node.ObjectNode;...@BodyParser.Of...
Handling XML requests and responses is easytoo.
build/deploy
sbtScala DSLUses build definitionAccurate incremental recompilationNot all sbt features are included in Play
sbt build definitionUse := to set a settingThere are a number of default settings.● Resovers● Source● Target● Hooks for Co...
Dependency Management with Ivyvia sbt
Add dependencies in Build.scalaSyntax:val appDependencies = Seq(  "org.apache.derby" % "derby" % "10.4.1.3")
Resolvers
Uses Maven2 and Scala Tools by defaultYou can add your own:resolvers += (   "Local Repository" at "file://"+Path.userHome....
Authentication and Authorization
● Play has its own authorization and  authentication● No JAAS compatibility● Only basic support, may not be enough for  en...
LinksAPI: http://www.playframework.com/documentation/api/2.1.0/java/index.htmlJava documentation: http://www.playframework...
Thank you
Play 2.0
Play 2.0
Play 2.0
Play 2.0
Play 2.0
Upcoming SlideShare
Loading in...5
×

Play 2.0

799

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
799
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Play 2.0

  1. 1. Play Framework2.1
  2. 2. OverviewDifferences from 1.0
  3. 3. Overview
  4. 4. ● Stateless web framework● RESTful-friendly● Asynchronous ability built in● LESS and CoffeeScript friendly too!
  5. 5. Differences from 1.0
  6. 6. Template engine1.0 2.0Groovy Pages Scala Templates
  7. 7. Persistence1.0 2.0Hibernate Ebean and Hibernate
  8. 8. Language Support1.0 2.0Java Java and Scala
  9. 9. Dynamic compilation1.0 2.0Byte code injection Dynamic compilation via SBT
  10. 10. And more...Reports on errors in JavaScriptDesigned for concurrent, long connectionsCRSF protection
  11. 11. ModulesjdbcanormjavaCorejavaJdbcjavaEbeanjavaJpafilters
  12. 12. Setup
  13. 13. Using Play from the consoleEnter an existing Play application directory andtype play
  14. 14. Using play in your IDEhttp://www.playframework.com/documentation/2.1.0/IDE
  15. 15. Creating an applicationplay new your_app_name
  16. 16. Example Time
  17. 17. ● Java and Scala source code goes here.● Can create own packages
  18. 18. Lets create a Play application...
  19. 19. Templates
  20. 20. Declared at the top of the file@(customer: models.Customer, orders: List[models.Order])
  21. 21. Are iterable...<ul>@for(p <- products) { <li>@p.getName() ($@p.getPrice())</li>}</ul>
  22. 22. Are conditional...@if(items.isEmpty()) { <h1>Nothing to display</h1>} else { <h1>@items.size() items!</h1>}
  23. 23. Can be reusable...@display(product: models.Product) = { @product.getName() ($@product.getPrice())}<ul>@for(product <- products) { @display(product)}</ul>
  24. 24. or@title(text: String) = @{ text.split( ).map(_.capitalize).mkString(" ")}<h1>@title("hello world")</h1>
  25. 25. Ability for server side comments@********************** This is a comment **********************@
  26. 26. Back to the example...
  27. 27. HTML Forms
  28. 28. HTML form submission data is easy to dealwith using the play.data.* packageUses Spring data binder to wrap a model(class)
  29. 29. To use:public class User { public String email; public String password;}Form<User> userForm = form(User.class);
  30. 30. Now, you can create a User from ahashmap or request objectMap<String,String> anyData = new HashMap();anyData.put("email", "bob@gmail.com");anyData.put("password", "secret");User user = userForm.bind(anyData).get();orUser user = userForm.bindFromRequest().get();
  31. 31. Can add constraints using JSR303implementationpublic class User { @Required public String email; public String password; public String validate() { if(authenticate(email,password) == null) { return "Invalid email or password"; } return null; }}
  32. 32. Custom handling of errors wheninvalid form submissionsif(userForm.hasErrors()) { return badRequest(form.render(userForm));} else { User user = userForm.get(); return ok("Got user " + user);}
  33. 33. FormHelpers
  34. 34. HTML Form creation is simple@helper.form(action = routes.Application.submit()) {}
  35. 35. Can add parameters too@helper.form(action = routes.Application.submit(),id -> "myForm") {}
  36. 36. 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"))}
  37. 37. Bad news: the markup isnt that pretty.Good news: you can take control
  38. 38. Back to the example...
  39. 39. Databases
  40. 40. By convention, the default database must becalled default.Other databases can have custom names.Only the h2 database driver is provided bydefault. Youll have to manually configure anyother drivers as an application dependency.
  41. 41. EBean and HibernateBoth Ebean and Hibernate are supportedEbean is natively supportedHibernate as an application dependency
  42. 42. EbeanEnabled in the conf/application.conf file***Play generates getter/setters to be availableat runtime, not compile time!***
  43. 43. Hibernate
  44. 44. Add Hibernate as a dependencyval appDependencies = Seq( "org.hibernate" % "hibernate-entitymanager" %"3.6.9.Final")
  45. 45. 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/persistencehttp://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>
  46. 46. Must manually denote a transactionusing @Transactional@Transactionalpublic static Result index() { ...}
  47. 47. Can retrieve current entity managerusing the play.db.jpa.JPA helperclasspublic static Company findById(Long id) { return JPA.em().find(Company.class, id);}
  48. 48. Working with JSON
  49. 49. JSON RequestContent-Type must specify text/json orapplication/json MIME type
  50. 50. 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); }}
  51. 51. 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); }}
  52. 52. Handling XML requests and responses is easytoo.
  53. 53. build/deploy
  54. 54. sbtScala DSLUses build definitionAccurate incremental recompilationNot all sbt features are included in Play
  55. 55. sbt build definitionUse := to set a settingThere are a number of default settings.● Resovers● Source● Target● Hooks for CoffeeScript, LESS, and JavaScript minification and generation
  56. 56. Dependency Management with Ivyvia sbt
  57. 57. Add dependencies in Build.scalaSyntax:val appDependencies = Seq( "org.apache.derby" % "derby" % "10.4.1.3")
  58. 58. Resolvers
  59. 59. Uses Maven2 and Scala Tools by defaultYou can add your own:resolvers += ( "Local Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository")
  60. 60. Authentication and Authorization
  61. 61. ● 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.
  62. 62. LinksAPI: http://www.playframework.com/documentation/api/2.1.0/java/index.htmlJava documentation: http://www.playframework.com/documentation/2.1.0/Home
  63. 63. Thank you

×