Spring MVC – CSS and JavaScript imports

In this series we will go through setting up a basic web structure that deals with importing resources (css/javascript), we’ll slowly progress this app in subsequent blog posts by adding layout/master page support as well as reading values from config files.  I will primarily use xml configuration for these setups, you can also do it strictly through code if you’d like, which I might write another blog post later on.

So, coming from a .NET (MVC)/Ruby-On-Rails world where right after start new project, everything is setup for you and ready to go, with Spring MVC, this was definitely not the case.  I struggled with the most basic things, such as how do I import css files? how do I use a common layout page so that I don’t have to repeat myself? how do I use config files? And after searching through the internet, it seems like most new comers to spring mvc are having these same issues as well, which is unfortunate because it is a powerful mvc framework but it seems like they gained that power by making it fat, ugly, and xml hungry Smile. Enough of that lets get started.

Importing css files:

Webjars (http://www.webjars.org/) allows to you to download and use common CSS and JavaScript files using any of the popular packaging tools. For our app we’ll use Maven, here is the pom.xml file to download bootstrap.css files.

pom1

I tried setting up the resource location using xml but that didn’t work, so here is how I did it through code. Add a POJO file to you project, lets call it WebConfig.java with the folloing contents.

webconfigPNG

With this you are ready to start importing css files that are listed in the pom.xml, which in our case is just the bootstrap files, here is the syntax for it:

<link rel="stylesheet" href="/webjars/bootstrap/3.1.1/css/bootstrap.min.css">

Lets also add a custom app.css and app.js files and see how we can set that up as well.  Now our project structure looks like this

projectbar

The “resources” folder is what we have used to put our resources, this is a special folder that spring understands how to deal with, but for some reason we still have to set it up in the dispatcher-servlet.xml file urgh…. (Convention over Configuration – spring please learn).  Here is the dispatcher-servlet.xml

mvc-dispatcher-servlet

We’ve added the “mvc” namespace and its associated schemaLocation information (don’t forget), then finally we can add the mapping and location information.  The two asterisk at the end means, add all folders underneath recursively, in our case both the css and js folders.

Now if you cross your fingers and hit run, everything should work and the resulting page should have all the css/javascript files that we’ve listed.

Here is the sample application on my GitHub