I have a problem with handling css files in Spring MVC. Something is wrong with the location and mapping of the css file.
If the css file is in:
-src
-main
+java
+resources
-webapp
-css
style.css
+WEB-INF
(Maven project)
I use:
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:annotation-driven/>
in dispatcher-servlet.xml, and access access it in the jsp with:
<head>
<title>Insert title here</title>
<link href="/css/style.css" rel="stylesheet" type="text/css">
</head>
To solve this problem so that your code will run with the actual paths you would use in production, use a
<base>tag in your JSP pages, like so:This will ensure that all of the rest of the relative paths in your JSP page can be represented using the full paths:
For further reading, here is a reference at the Mozilla Developer Center on the usage of the HTML base element. Additionally, this blog post may also be helpful in giving you a perspective on working with client-side code, especially if you work with Web designers who are not Java developers.
NOTE: As an aside, if you combine @gigadot’s proposed solution to use c:url tags with the base tag, then it will save you the trouble of needing to edit every single link on your site and cluttering the HTML, while still making the base tag be dynamic so that if you change the context path, it will still be reflected everywhere, but in a manner that doesn’t bind you so tightly to the framework.
I’m linking to that answer so that the credit for using the
<c:urltag goes to @gigadot, yet documenting it here so that others can benefit from the combined knowledge of using both together.