Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

Jump into Java microframeworks, Part 4: Play

Matthew Tyson | March 18, 2016
A closer look at Java's original, ultra-lightweight web development stack

Look again at the routes file and notice this line:

GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

This maps GET requests to the /assets URL to the built-in controller called Assets. It uses the versioned method, routing them via the first argument to /public. Versioned means that these assets will be tagged with a cache-busting string when a new version is deployed in production. As a result, clients will always get the most recent version. (Note that the second argument, file:Asset, is required for versioning to work. Also note that versioning doesn't work in dev mode!)

For this solution to work, our JavaScript files need to be in the /public folder. Fortunately, Play already has a /javascripts folder, which includes a friendly hello.js to get us started. We'll use this script shortly. 

Adding JavaScript elements

The first thing we'll do is add jQuery to the application dependencies. We could paste in jQuery to /public, or reference a public CDN. An easier option is to pull the dependency into our project using WebJars. Like Ninja, Play has built-in support for WebJars. To add jQuery, we'll modify our build.sbt to include it, as seen in Listing 10. Just for fun, I've used the bleeding-edge (as of this writing) jQuery version in Alpha (3.0.0-alpha1).

Listing 10. Adding jQuery WebJar to build.sbt

libraryDependencies ++= Seq( javaJdbc, cache, javaWs, "mysql" % "mysql-connector-java" % "5.1.18", "org.webjars" %% "webjars-play" % "2.4.0" "org.webjars" % "jquery" % "3.0.0-alpha1" )

Notice that I actually added two new dependencies: the Play WebJar library, and a reference to the jQuery webjar.

Now we just need to reference the jQuery webjar from our HTML header. Listing 11 shows how to do that. We'll add the line from Listing 8 to main.html.scala. Just make sure to put the line before the hello.js include (because hello.js is going to reference jQuery here in just a moment).

Listing 11. index.html.scala: Adding jQuery webjar reference


In Listing 11 we use Play's support for WebJar (added in Listing 7) to refer to the jQuery library. Lastly, we need to map a route for it in routes. We only have to do this the first time we set up WebJar. Listing 12 shows the route we want.

Listing 12. Adding WebJar Route

GET     /webjars/*file          

To find the WebJar you need, go to and type in what you're looking for. Then, select your build tool and cut-and-paste the dependency string into your build file. 


Previous Page  1  2  3  4  5  6  7  Next Page 

Sign up for CIO Asia eNewsletters.