Context path in URIs of static resources, do I rea

2019-05-15 20:11发布

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.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-15 20:43

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
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-05-15 20:54

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.

查看更多
登录 后发表回答