3

I have a simple web app

webapp
   static
       images
            - a.gif
       pages
            - test.html
   WEB-INF
       pages
            - test.jsp

in test.html, there is

<img src="/static/images/a.gif"/>

the problem is that the image is not displaying until I change the uri to

<img src="/web app name/static/images/a.gif"/>

but I'm loading test.html at URI

http://server/web app name/static/pages/test.html

I configured static resources mapping in my web.xml as follows.

<servlet>
    <servlet-name>springWeb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-web.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>springWeb</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>resourceServlet</servlet-name>
    <servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>resourceServlet</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>

Am I missing anything? I do want to keep those static resources within the app in DEV phase instead of moving them to a HTTP server.

Thanks a lot.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303
jnj
  • 755
  • 2
  • 11
  • 23

2 Answers2

6

It's good practice to use either the spring:url tag or the JSTL c:url tag to wrap URLs in your HTML for this very reason. Those tags will automatically add the context path.

For example:

<img src="<spring:url value='/static/images/a.gif'/>"/>

Alternatively you can use a context path of "" in development. That way your urls would match production. The way this is done is different for each servlet container - for example for Tomcat you would deploy your app to webapps/ROOT.

sourcedelica
  • 23,940
  • 7
  • 66
  • 74
2

One way to make it a bit more generic is to use

<img src="<%=request.getContextPath()%>/static/images/a.gif"/>

Alternative if you know your directory structure you could use relative urls, such as

static/images/a.gif
../static/images/a.gif
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • Since the dir structure is going to be constant, as per the OP, it's better to use the alternative static/images/a.gif. The problem OP facing is because of adding a leading slash. – asgs Feb 21 '11 at 14:03
  • 1
    +1, though `${pageContext.request.contextPath}` is even better. – Steven Benitez Apr 09 '11 at 18:52