Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

Jump into Java microframeworks, Part 1

Matthew Tyson | Oct. 28, 2015
Go extra lightweight, with Java microframeworks Spark, Ninja, and Play

Set up and run the project

First, Ctrl-d to stop the running server, and then type exit to drop back to the command-line. Type: activator ui. Now open: (it should open automatically for you), and you will be looking at your projects configuration page in the UI. Click Code View & open in IDE in the main content window, as seen in Figure 7. Hit Create Eclipse Project as seen in Figure 8, then return to the command-line, and kill off the UI process (ctrl-c). You can now import the project into Eclipse. If you would like to get the dependency sources, run activator eclipse with-source=true from your project directory.

java microframeworksp1 fig9
Figure 9. Activator code view and open in IDE

java microframeworksp1 fig10
Figure 10. Create the Eclipse project

You'll notice that Play has dropped in a lot of packages; in this regard it's more akin to Ninja than Spark.

Now type activator run, and you're ready to start coding.

Routes and controllers in Play

After unpacking Ninja and Spark, you'll know that Play must include a centralized routing file. Look at conf/routes. Here again we have the method, path, handler pattern – this time in a plain text format, as seen in Listing 13.

Listing 13. A Play route

GET     /      controllers.Application.index()

At a glance, we can see that our GET root URL calls are going to be handled by package controllers, class Application, and method index(). Notice that the index() method for Application looks like Listing 14.

Listing 14. A Play controller

public Result index() {

        return ok(views.html.index.render("Your new application is ready."));


So the index() method returns a Result object, and the method uses the ok helper class to return a successful HTTP result, where the content is specified by the argument. As an alternative example, if we wanted to send a 401 unauthorized HTTP status, we could use unauthorized("no") - you can see this in the sample code for this article, mapped to the /no URL path.

The argument passed to the ok method is the body of the response, and it makes use of the views.html.index.render() call. That call resolves a template, similar to how Ninja and Spark work. Play has the ability to swap in various templating technologies; but for now, let's take a quick look at the default Scala template.

Play's Scala template

Listing 14 shows the views/index.scala.html file:


Previous Page  1  2  3  4  5  6  7  8  9  10  Next Page 

Sign up for CIO Asia eNewsletters.