0

When you need to reference a resource file from a JSP file within SpringMVC you have to pass an absolute url for the resource, which is traditionally done with either <c:url ... or href="${pageContext.request.contextPath}/css/....

However, how do pass absolute urls within my CSS and JS files? In CSS this can be necessary at times you use a url for a property. In my JS files I may need to make an AJAX call to an absolute URL that I define somewhere. In both of these instances these URLS can change at different times, but Googling has not pointed me to the best way to handle cases like these. I wouldn't be above adding a new maven plugin or some other JS or CSS compiler to achieve this.

1
  • contextPath doesn't mean absolute url. Commented Apr 14, 2014 at 6:53

1 Answer 1

1

CSS URLs don't need to be absolute, because the URLs are not resolved relative to the path of the current page, but relative to the path of the CSS file itself.

For JS, you simply have to define, for example, the base URL in a global variable, from your base JSP template, and reuse that base URL from your JS files:

In your JSP:

<script>var BASE_URL = "<c:url value='/' />";</script>
<script src="someFile.js"></script>

In your JS file:

$('#foo').load(BASE_URL + 'some/path.html');
Sign up to request clarification or add additional context in comments.

3 Comments

CSS: okay, that makes sense. I didn't realize that I could use a relative path and make use of something like ../images/example.jpg. For JS: I've thought of doing that, while I'm not above it; it seems somewhat messy. I'll do it if push comes to shove, but I'd prefer not to. Is there any alternative?
You could parse the current location somehow and deduce the base URL, if you're sure your app will always be deployed in a non-root context.
I think I'll go with your original suggestion, it's clearly easier and probably more reliable. (It won't take much to implement either, as I can just do it within the header site-tile.) Mucho apreciado, amigo!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.