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

So item 3 is saying: You want an implementation of the Route.handle method? Well here's an implementation that takes two arguments, and returns a String: "Hello, JavaWorld."

If you wanted to make use of the arguments within the lambda body, you could do as I've done in Listing 11:

Listing 11. Using an argument in Spark lambda

Spark.get("/jw", (req, res) -> "Hello JavaWorld: " + req.queryParams("songwriter"));

And then restart the server by stopping the Spark main process in Eclipse (see Figure 6), and refreshing the browser with a query param: http://localhost:4567/jw?songwriter=paul_simon. You should see your songwriting choice reflected in the browser output.

Java Micro Frameworks, Part 1.
Figure 7. Stopping the Spark main process in Eclipse

In this short example we have accessed the req argument from inside the lambda expression, and you've also had your first look at the Spark request model. Next let's take a look at how Spark handles views.

Multi-line lambdas

For your interest, here's the multi-line form of a Java lambda:

Spark.get("/jw", (req, res) -> { 

    		String ret = req.queryParams("songwriter") + " " + req.queryParams("band");

    		return "Hello JavaWorld: " + ret;


Spark views

Of course, we don't want to generate our responses inline in code (if we did, we'd still be writing CGI). Spark supports a wide range of view technologies via plugins. Thymeleaf is a templating system that is often underrated, so let's see how it handles Spark's views.

Start by adding the spark-thymeleaf bridge to your POM, as shown in Listing 12.

Listing 12. Spark-Thymeleaf bridge






Next, create a new mapping in

Listing 13, A model/view mapping in Spark

Map map = new HashMap();

map.put("group", "Fleetwood Mac");

Spark.get("/thyme", (rq, rs) -> new ModelAndView(map, "template"), new ThymeleafTemplateEngine());

This mapping basically says: when a GET request hits /thyme, handle it with the defined objects. In this case, the second argument is a ModelAndView, and we are passing it a map and a name, in this case "template". The third argument is the TemplateEngine implementation that we pulled in with Maven, ThymeleafTemplateEngine.

Spark will take the Map data, the template, and the template engine, and combine them into a rendered view.

The default is for the TemplateResolver to find your templates on the classpath under /templates, with an .html extension. For expedience, we'll just add a /templates directory under src/main/resources, then add that to the source classpath in Eclipse. The steps for that are: project-->properties-->Java Build Path-->Source-->Add Folder, as in Figure 8.


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

Sign up for CIO Asia eNewsletters.