Pages

Monday, September 2, 2013

How to include external CSS file in JSP with SpringMVC

In previous post we solved the issue of loading JSPs with SpringMVC without providing the file extension. When we solve this issue, there might be some possibilities that the external CSS files not loading properly and you might get the following error:




So the question is, how to include external CSS file or Bootstrap CSS file properly into JSP??

It's easy as adding few lines in your SpringMVC 3 XML file! Before that, let's see what the issue is.

When you keep your CSS/ images/ JS files inside your web folder and try to load it in JSP, it goes to Spring's Dispatcher Servlet. There is no mapping for those files and Spring won't load them.

Add the following line to the dispatcher-servlet.xml and put all the static resources like CSS, images & JavaScript files inside a folder inside your web folder as mentioned below:
















And the JSP file needs to access the external CSS file as follows. In this example, I've used Bootstrap, but same applicable for your own CSS as well.



Now a final tip before finishing- did you notice the first line of the spring config file? Make sure you have the line <mvc:annotation-driven/> in place when you are using annotation based controller definition in your source. Try without that line and you'll have a frustrating situation where the resources will work fine and the JSPs won't be loading properly!

The reason is this. When you add the  line, SpringMVC adds its own handler mapping and the default DispatcherServlet's mappings  are broken. Therefore other handler mappings should be declared explicitly, either by  or manually as beans. So adding <mvc:annotation-driven/> does the trick for you. That's all!



No comments:

Post a Comment