Play Framework Essentials
()
About this ebook
Play is a framework to write web applications using Scala or Java. It provides a productive development environment, allowing you to just hit the "refresh" button in your browser to compile your changes and reload the application. Because of its stateless nature, the framework makes it easy to build applications that scale. Play provides a reactive programming model to harness the event-driven HTTP layer.
This book provides a step-by-step walkthrough of how to build a complete web application following best application development practices using Play framework 2. All aspects specific to web-oriented architectures are covered: the HTTP layer, JSON manipulation, HTML templating, asset compression and concatenation, form submission, content negotiation, security, and HTTP streaming. The book will also provide detailed architectural insights into Play framework to give you a better understanding in order to successfully build scalable applications.
Related to Play Framework Essentials
Related ebooks
Building Single-page Web Apps with Meteor Rating: 5 out of 5 stars5/5Apache Solr PHP Integration Rating: 0 out of 5 stars0 ratingsAndroid Application Programming with OpenCV Rating: 3 out of 5 stars3/5Meteor Design Patterns Rating: 0 out of 5 stars0 ratingsAdministrating Solr Rating: 0 out of 5 stars0 ratingsJavaScript Concurrency Rating: 0 out of 5 stars0 ratingsRedmine Plugin Extension and Development Rating: 0 out of 5 stars0 ratingsMaster Hacking Plan Rating: 0 out of 5 stars0 ratingsDeveloping Web Applications with Apache, MySQL, memcached, and Perl Rating: 0 out of 5 stars0 ratingsBeginning Mobile Application Development in the Cloud Rating: 0 out of 5 stars0 ratingsPhantomJS Cookbook Rating: 0 out of 5 stars0 ratingsjQuery Hotshot Rating: 0 out of 5 stars0 ratingsMastering Android Wear Application Development Rating: 0 out of 5 stars0 ratingsInstant HTML5 Geolocation How-To Rating: 0 out of 5 stars0 ratingsEmber.js in Action Rating: 0 out of 5 stars0 ratingsManaging Open Source Projects: A Wiley Tech Brief Rating: 4 out of 5 stars4/5Mastering Ninject for Dependency Injection Rating: 0 out of 5 stars0 ratingsMastering Android NDK Rating: 0 out of 5 stars0 ratingsJava 9 with JShell Rating: 0 out of 5 stars0 ratingsPHP Programming Solutions Rating: 0 out of 5 stars0 ratingsInstant StyleCop Code Analysis How-to Rating: 0 out of 5 stars0 ratingsJavaScript Everywhere Second Edition Rating: 0 out of 5 stars0 ratingsInstant Highcharts Rating: 0 out of 5 stars0 ratingsDatabase Security A Complete Guide - 2020 Edition Rating: 0 out of 5 stars0 ratingsKernel Based Virtual Machine A Complete Guide - 2021 Edition Rating: 0 out of 5 stars0 ratingsInstant Building Multi-Page Forms with Yii How-to Rating: 0 out of 5 stars0 ratingsiOS SDK Complete Self-Assessment Guide Rating: 0 out of 5 stars0 ratingsThe New Frontier In Web Api Programming Rating: 0 out of 5 stars0 ratingsMulti-Tier Application Programming with PHP: Practical Guide for Architects and Programmers Rating: 0 out of 5 stars0 ratings
Programming For You
Game Development with Unreal Engine 5: Learn the Basics of Game Development in Unreal Engine 5 (English Edition) Rating: 0 out of 5 stars0 ratingsPython: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5The Unofficial Guide to Open Broadcaster Software: OBS: The World's Most Popular Free Live-Streaming Application Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Modern C++ for Absolute Beginners: A Friendly Introduction to C++ Programming Language and C++11 to C++20 Standards Rating: 0 out of 5 stars0 ratingsLearn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Python Projects for Beginners: A Ten-Week Bootcamp Approach to Python Programming Rating: 0 out of 5 stars0 ratingsCoding All-in-One For Dummies Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Beginning Programming with Python For Dummies Rating: 3 out of 5 stars3/5Web Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5
Reviews for Play Framework Essentials
0 ratings0 reviews
Book preview
Play Framework Essentials - Julien Richard-Foy
Table of Contents
Play Framework Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Building a Web Service
Play – a framework used to write web applications
Bootstrapping a Play application
Play applications' layout
URL routing
Route path parameters
Parameters type coercion
Parameters with fixed values
Query string parameters
Default values of query string parameters
Trying the routes
Building HTTP responses
Serializing application data in JSON
Reading JSON requests
Validating JSON data
Handling optional values and recursive types
Summary
2. Persisting Data and Testing
Testing your web service
Writing and running tests
Testing the HTTP layer
Using the reverse router to generate URLs
Running a fake Play application
Effectively writing HTTP tests
Persisting data
Using a relational database
Getting a reference to the currently running application
Using a database management library
Using Slick in Scala
Using JPA in Java
Integrating with other persistence technologies
Populating the database with fixtures
The application's Global object
Managing database schema evolutions
Using an in-memory database for tests
Summary
3. Turning a Web Service into a Web Application
Delta between a web service and a web application
Using the template engine to build web pages
Inserting dynamic values
Looping and branching
Reusing document fragments
Comments
Import statements
Generating HTML forms
Repeated and nested fields
Reading and validating HTML form data
Handling the HTML form submission
Validating the HTML form data
The Scala form validation API
The Java form validation API
Optional and mandatory fields
Sharing JSON validation and HTML form validation rules
Handling content negotiation
Putting things together
Writing web user interface tests
Summary
4. Integrating with Client-side Technologies
Philosophy of Play regarding client-side technologies
Serving static assets
Sprinkling some JavaScript and CSS
Using the JavaScript reverse router
Managing assets from the build system
Producing web assets
Pipelining web assets' transformations
Concatenating and minifying JavaScript files
Gzipping assets
Fingerprinting assets
Managing JavaScript dependencies
Running JavaScript tests
Summary
5. Reactively Handling Long-running Requests
Play application's execution model
Scaling up your server
Embracing non-blocking APIs
Managing execution contexts
Writing incremental computations using iteratees
Streaming results using enumerators
Manipulating data streams by combining iteratees, enumerators, and enumeratees
Unidirectional streaming with server-sent events
Preparing the ground
Transforming streams of data using enumeratees
Implementing a publish/subscribe system using Akka
Bidirectional streaming with WebSockets
Controlling the data flow
Summary
6. Leveraging the Play Stack – Security, Internationalization, Cache, and the HTTP Client
Handling security concerns
Authentication
Cross-site scripting
Cross-site request forgery
HTTP request filters
Using the CSRF filter
Enabling HTTPS
Saving computation time using cache
Serving content in several languages
Calling remote web services
Background – the OAuth 2.0 protocol
Integrating your application with your preferred social network
Implementing the OAuth client
Calling the HTTP API of your preferred social network
Summary
7. Scaling Your Codebase and Deploying Your Application
Making an action's logic reusable and composable with action builders
Capturing the logic of actions that use blocking APIs
Capturing the logic of actions that require authentication
Combining action builders
Modularizing your code
Applying the inversion of control principle
Using dynamic calls in route definitions
Setting up a dependency injection system
Making your code injectable
Mocking components
Splitting your code into several artifacts
Splitting your controller layer into several artifacts
Application deployment
Deploying to your dedicated infrastructure
Deploying to the cloud
Handling per environment configuration
Overriding configuration settings using Java system properties
Using different configuration files
Summary
Index
Play Framework Essentials
Play Framework Essentials
Copyright © 2014 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2014
Production reference: 1190914
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-240-0
www.packtpub.com
Cover image by Pratyush Mohanta (<tysoncinematics@gmail.com>)
Credits
Author
Julien Richard-Foy
Reviewers
Shannon –jj Behrens
Cédric Chantepie
Commissioning Editor
Amarabha Banerjee
Acquisition Editor
Vinay Argekar
Content Development Editor
Akashdeep Kundu
Technical Editors
Indrajit A. Das
Taabish Khan
Humera Shaikh
Copy Editors
Deepa Nambiar
Laxmi Subramanian
Project Coordinator
Kartik Vedam
Proofreaders
Simran Bhogal
Maria Gould
Ameesha Green
Paul Hindle
Indexers
Monica Ajmera Mehta
Tejal Soni
Graphics
Abhinash Sahu
Production Coordinators
Aparna Bhagat
Manu Joseph
Cover Work
Aparna Bhagat
About the Author
Julien Richard-Foy likes to design code that seamlessly expresses the ideas he has in mind. He likes finding the right level of abstraction, separating concerns, or whatever else that makes the code easy to reason about, to maintain and to grow.
He works at Zengularity, the company that created the Play framework, and actively contributes to the evolution of the framework.
He aims at working on technically challenging and innovative projects that have a positive environmental or social impact on the world.
About the Reviewers
Shannon -jj Behrens is a staff software engineer at Twitter, working in the Infrastructure and Operations department. He lives in Concord, California, with his lovely wife and seven lovely children. He's well known for his impeccable sense of modesty, world-renowned taste in T-shirts, and poor sense of humor. He blogs at http://jjinux.blogspot.com on a wide variety of topics such as Python, Ruby, Scala, Linux, open source software, the Web, and lesser-known programming languages.
Cédric Chantepie is an IT system architect, with varied development experience (C/C++/ObjC, LISP, JavaEE, Haskell, and Scala), obsessed by software quality (CI, testing, and so on), and involved in open source projects.
www.PacktPub.com
Support files, eBooks, discount offers, and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Preface
The Web allows you to make applications that can be used from anywhere in the world as long as there is an Internet connection. The Play framework has been designed to embrace the characteristics of modern web applications such as handling long-running requests and manipulating data streams.
This book shows you how to write such web applications using Play. I designed it to be progressive so that you can quickly write a running application and then enhance it to benefit from all the components of the Play stack, or from lower-level APIs if you need more control.
Code examples are given in both Scala 2.10 and Java 8 (except for some APIs that have no Java counterpart). You can find executable applications based on the code examples of the book at http://github.com/julienrf/pfe-samples.
Finally, I encourage you to browse the API documentation of the framework to complete the content of this book. You can find it online at http://www.playframework.com/documentation.
What this book covers
Chapter 1, Building a Web Service, explains how to turn an application into a web service by exposing its resources and features as HTTP endpoints.
Chapter 2, Persisting Data and Testing, shows how you can integrate a persistence system to your Play application and how to write specifications of your HTTP layer.
Chapter 3, Turning a Web Service into a Web Application, goes one step further by showing you how the Play framework can help you to define HTML pages for your application and handle HTML forms.
Chapter 4, Integrating with Client-side Technologies, gives you insights on ways to manage the production of web assets from the build system of your Play application.
Chapter 5, Reactively Handling Long-running Requests, dives deeper in the framework internals and explains how to leverage its reactive programming model to manipulate data streams.
Chapter 6, Leveraging the Play Stack – Security, Internationalization, Cache, and the HTTP Client, presents additional components that are part of the Play stack.
Chapter 7, Scaling Your Codebase and Deploying Your Application, looks back at the code of your application and provides patterns to keep it modular and easy to maintain. It also explains how to deploy your application in a production environment.
What you need for this book
The content of this book is based on Play 2.3.x and shows both Scala and Java APIs. Though this book uses Java 8, Play supports Java 6, so all you need to start developing a Play application is at least JDK 6. Chapter 1, Building a Web Service, explains how to install activator, a command-line tool to generate starter application skeletons and then manage their life cycle (running, testing, and so on). Finally, you also need a web browser to use your applications.
Who this book is for
This book targets Java or Scala developers who already have some knowledge of web development.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Source files are under the app/ directory.
A block of code is set as follows:
val index = Action {
Ok(Just Play Scala
)
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
val index = Action {
Ok
(Just Play Scala
)
}
Any command-line input or output is written as follows:
$ curl -v http://localhost:9000/items
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: If everything works fine, your browser should show a page titled Just Play Scala (or Just Play Java).
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Building a Web Service
This chapter will cover the following topics:
Bootstrapping a Play project
Understanding the different pieces of a Play project
Mapping URLs to your service entry points
Serving JSON responses and reading and validating JSON requests
Play – a framework used to write web applications
Play is a framework used to write web applications. As shown in the following diagram, a web application is based on a client-server architecture and uses the HTTP protocol for communication:
Web-oriented architecture
Users have the role of clients and make HTTP requests to servers to interact with the application. The servers process their requests and send them a response. Along the way, the web application might need to make use of various databases or perhaps other web services. This entire process is depicted in the following diagram:
The Play framework's overall architecture
This book will show you how Play can help you to write such web applications. The preceding diagram shows a first big picture of the framework's overall architecture. We will refine this picture as we read through this