Sunday, September 14, 2014

SparkJava and Webjars

I've been playing around with Per Wendel's Spark framework. It's a micro framework inspired by Sinatra and it's in the same vein of node.js and ruby-on-rails. Just the thing is, Spark is Java and by being Java, the whole Java ecosystem is available.

I started learning Spark via the readme section of the site. Once you get through the basics, you start working in your favorite Java stuff. For me, the first thing I wanted to work in is Webjars.

Webjars is this thing we it pack jars with client-side libraries. This allows us to manage client-side libraries using various Java build tools like maven, ivy or gradle.

Adding webjars into an maven project is painless. It's a dependency. Here's a webjar for bootstrap3:


With the webjar added. We now need to tell Spark about it and serve them files. This took me a couple of hours to make it work. I had to figure out that webjars unpack to /META-INF/resources folder and tell Spark about it. It also helped that I looked at Spark's source code and realized that is a special Java servelet.

// Serve our client-side files from here

And reference it in our template like this:
<link rel='stylesheet' href='webjars/bootstrap/3.1.0/css/bootstrap.min.css'>

There. Spark app with webjars.