Wednesday, July 27, 2011

Context root relative URLs using Spring's <spring:url>

While developing web applications the common problem is to reference the static resources like js, stylesheets,images in JSPs from the relative URLs.
Suppose in your project you have the following structure.
MyApp
        src
        WebContent
              home.jsp
              jsp
                  createUser.jsp
              js
                  util.js
              css
                   style.css
              images
                      logo.jpg
             WEB-INF
                          ...
             .......

So here if your current URL is http://localhost:8080/MyApp/home.do, you need to reference static resources as follows:

<script type="text/javascript" src="js/util.js"/>
Suppose your current URL is http://localhost:8080/MyApp/jsp/createUser.do, you need to reference static resources as follows:

<script type="text/javascript" src="../js/util.js"/>

This becomes messy to reference the static resources like this.

Spring framewrok is providing a custom tag <spring:url> to resolve this issue.
<spring:url> tag resolves the path from context root. So you can always give the path for static resources from context root irrespective of current URL.

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<script type="text/javascript" src='<spring:url value="/js/ajax.js" htmlEscape="true"/>'></script>

You can also pass the query parameters like this:
<s:url value="/messages/" var="messages_url" htmlEscape="true">
<s:param name="name" value="siva"></s:param>
</s:url>
<a href="${messages_url}">Messages</a>
This results in <a href="/MyApp/messages/?name=siva">Messages</a>

If you want to pass the param values as part of URI you can do like this:
<s:url value="/messages/{name}" var="messages_url" htmlEscape="true">
<s:param name="name" value="siva"></s:param>
</s:url>
<a href="${messages_url}">Messages</a>
This results in <a href="/MyApp/messages/siva">Messages</a>

This tag helped me a lot while developing web application following REST approach.

4 comments:

  1. Hello Siva,

    Do you have any idea how to do with url('../img.jpg') inside the included css file?

    ReplyDelete
  2. Hi siva
    It is great blog.Great effort.Thanks for sharing your useful information.Good.

    ReplyDelete
  3. Hi Siva,

    To make this
    <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
    working which tag library do you need?

    I get the following error

    The absolute uri: http://www.springframework.org/tags cannot be resolved in either web.xml or the jar files deployed with this application

    Can you please help?

    Thanks,
    Krunal
    iamkrunal@yahoo.com

    ReplyDelete
  4. The spring.tld will be in spring-webmvc-(version).jar file.
    If spring-webmvc.jar is in WEB-INF/lib, you don't need to configure it in web.xml explicitly.

    -Siva

    ReplyDelete