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 . Enough of that lets get started.
Importing css files:
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.
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
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
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.
Here is the sample application on my GitHub