Typesafe Activator

Play + Java + CRUD

Play + Java + CRUD

hakandilek
Source
September 2, 2014
sample playframework java crud

This template is an easy way to get started with Play Framework, Java, using play2-crud module

How to get "Play + Java + CRUD" on your computer

There are several ways to get this template.

Option 1: Choose play2-crud-activator in the Typesafe Activator UI.

Already have Typesafe Activator (get it here)? Launch the UI then search for play2-crud-activator in the list of templates.

Option 2: Download the play2-crud-activator project as a zip archive

If you haven't installed Activator, you can get the code by downloading the template bundle for play2-crud-activator.

  1. Download the Template Bundle for "Play + Java + CRUD"
  2. Extract the downloaded zip file to your system
  3. The bundle includes a small bootstrap script that can start Activator. To start Typesafe Activator's UI:

    In your File Explorer, navigate into the directory that the template was extracted to, right-click on the file named "activator.bat", then select "Open", and if prompted with a warning, click to continue:

    Or from a command line:

     C:\Users\typesafe\play2-crud-activator> activator ui 
    This will start Typesafe Activator and open this template in your browser.

Option 3: Create a play2-crud-activator project from the command line

If you have Typesafe Activator, use its command line mode to create a new project from this template. Type activator new PROJECTNAME play2-crud-activator on the command line.

Option 4: View the template source

The creator of this template maintains it at https://github.com/hakandilek/play2-crud-activator#master.

Option 5: Preview the tutorial below

We've included the text of this template's tutorial below, but it may work better if you view it inside Activator on your computer. Activator tutorials are often designed to be interactive.

Preview the tutorial

View the App

THIS TUTORIAL IS UNDER CONSTRUCTION!
Once the application has been compiled and the server started, your application can be accessed at: http://localhost:9000
Check in Run to see the server status.
This example app stores and displays a list of "Bar" objects in a database.

Handling Requests

When you make an HTTP request to that URL, the Play server figures out what code to execute which will handle the request and return a response. In this application the request handler for requests to the root URL (e.g. "/") are handled by a Java Controller. You can use Java and Scala to create your controllers.
Controllers asynchronously return HTTP responses of any content type (i.e. HTML, JSON, binary). To see a JSON response produced by a Scala controller, click the "Get JSON Message" button. This uses AJAX via jQuery to get data from the server and then display that on the web page.

Code Overview

A Play application has very few required files. This example tries to illustrate a number of key concepts in Play so it has a handful of files to explain. The app directory contains the application's source code, including Java, Scala, server-side templates, and server-side compiled assets for the browser (e.g. JavaScript, CoffeeScript, LESS). The conf directory contains the application.conf config file and the routes file. The project directory contains the SBT build information for the app. The default place for static assets (e.g. images, HTML, CSS, JavaScript) is the public directory. Unit, functional, and integration tests (Java and Scala) go in the test directory.

HTTP Routing

The routes file contains mappings between HTTP request verbs & paths and the code that controller method that handles the requests. Route paths can be parametrized to support RESTful style URLs. The following mapping will handle HTTP GET requests to "/" using the controllers.MainController.index method:

GET   /    controllers.MainController.index
You can try out the routing by first making a request to an unmatched route, like: http://localhost:9000/foo
This should produce an error because there isn't a route that matches the request. Then edit the routes to include a new route:
GET   /foo    controllers.MainController.index
Now retry the request and you should see the default index page.
By default the routes are compiled by Play so that they can be used in a type-safe way. This prevents issues caused by incorrect URL usages.

Controllers

HTTP GET requests to http://localhost:9000/ are handled by the index method defined in the MainController.java file. This static method returns a Result which in this case consists of a server-side rendered template and an HTTP 200 response which is represented by the ok method call. You can also use non-static methods along with Dependency Injection frameworks like Spring, Guice, and CDI.
You can change the "Hello from Java" string in MainController.java a different value, like "Hello from Play", then save the file and reload the index page in your browser. Play will automatically recompile the controller and you should immediately see your changes.
If your changes result in a compile error you will see the error in your browser (after a refresh) and in the Compile Plugin. Try it by removing one of the double-quotes in the index method's string, save the file, and reload the index page. Fix the error before you continue.
There is also a Scala controller which provides an example JSON service. (Note: Play also has built-in JSON support in Java controllers.) You can see the JSON by opening http://localhost:9000/message in your browser. This route is also mapped in the routes file but this time the request is handled by the MessageController.scala file's getMessage function. This controller returns an Action which is responsible for producing a HTTP response. In this case the response is a case class which is serialized to JSON. You will also notice the MessageController contains a function called javascriptRoutes which provides a mechanism for using the type-safe routes in JavaScript.

Templates

The MainController.index method uses a template which is compiled by Play into a function. The source is in the index.scala.html file and is available by calling the views.html.index.render function. This template takes a parameter of a String so the compiled function also takes a String parameter. The default templating language in Play is Scala, but a number of other templating languages (like Java, Groovy, and Dust) can also be plugged in.
The index template uses the main template by calling the main function with the required parameters.
Notice that the templates do not use hard-coded URLs and instead use Play's reverse routing, like:

@routes.Assets.at("images/favicon.png")
This provides a type-safe way to specify URLs in an application. If the URL to a file changes, then automatically, the new value will be used throughout all of the URL references. You can use the reverse router anywhere in your code, like redirects in controllers.
Like controllers (and all source code in Play) you can make changes to templates which triggers a recompile. Then simply refresh the page to see the changes. Try it out by making a change to the index template, saving the file, and then refreshing the index page in your browser.

Static Assets

This application has a route to handle loading static assets from the public directory:

GET /assets/*file controllers.Assets.at(path="/public", file)
A request to http://localhost:9000/assets/images/favicon.png will use this route to find the favicon.png file in the public/images directory.
You can put any static assets into the public directory and have them accessible in this way.

Asset Compiler

Modern web applications often use compilers to generate static assets for the browser. Play has a built-in asset compiler which can automatically syntax check & minify JavaScript, compile CoffeeScript to JavaScript, and compile LESS to CSS. You can also plug in other compilers into the Play's asset compiler.
This application contains two example uses of the asset compiler. The index.js file will automatically be syntax checked and minified. The minified version is can be referenced in a template with:

<script type='text/javascript'
src='@routes.Assets.at("javascripts/index.min.js")'>
</script>
You can also put CoffeeScript files with a .coffee extension in the app/assets/javascripts directory to have them automatically compiled and minified.
The index.less file will be compiled into both a index.css and a index.min.css file.

Test the App

This application includes a number of tests which are automatically run after each successful compile. You can see the test results in the Test plugin. Due to changes that you may have made to your application source code, some of the tests might now be failing. The source for the tests is located in the test directory and contains both Java and Scala tests. The test/MainControllerTest.java Java class contains a number of unit and functional tests for the MainController. The IntegrationTest.java file contains an test which uses Solenium to test the actual UI in a browser. The default testing framework for Java in Play is JUnit, but you can plug any testing framework in.
The MessageControllerSpec.scala file contains a functional test for the MessageController.
If you modify a test and save the changes, then the tests will automatically be re-run.

SBT Build

SBT is the build system underneath Play applications. It is responsible for resolving dependencies, compiling the project, running the tests, etc. The primary build definition file is the Build.scala file. In that file you will see a comma-seperated list of dependencies which can be modified to suit your needs. Play includes a number of libraries which can selectively be turned on/off. For instance if you want to use JPA with Play, uncomment the javaJpa dependency. You can also add your own dependencies in the SBT form:

"group" % "artifact" % "version"

Further Learning

The Play Documentation contains much more exhaustive details and also covers a number of other topics which haven't been addressed in this tutorial.
StackOverflow is a great place ask questions about Play.
The play-framework Google Group is a great place to discuss Play.

comments powered by Disqus