Pages

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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!



Error 404 Not Found when calling url without file extension in SpringMVC

If you are new to web frameworks and trying some sample programs available in the net, you might face this error at initial stages.



If you try the same with the extension, it will work:

/testMVC/index.htm OR /testMVC/index.jsp

In this scenario, have a look at the  in web.xml. If the url pattern is something like



<url-pattern>*.htm</url-pattern> OR <url-pattern>*.jsp</url-pattern>

you might need to do a change to make it working without the extension.

If you want to make sure it works without the extension, you need to change in the web.xml as follows:
Wondering what is the change? We are telling Spring servlet to take care of all url patterns. So all the requests will be handled by Spring. When you do this fix and make it working, you might encounter another issue which we'll see in the next post. Look forward to solve the issue: Unable to load external CSS file in SpringMVC