Context path in static resource URI, do you really need to specify it?

I have a simple web application

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 displayed until I change uri to

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

but I load test.html in a URI

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

I configured static resource 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>

Did I miss something? I want to store these static resources in an application in the DEV phase instead of moving them to an HTTP server.

Many thanks.

+3
source share
2 answers

It is good practice to use the spring: url tag or the JLL c: url tag to transfer URLs to your HTML for this reason. These tags will automatically add the path to the context.

For instance:

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

"" . , URL- . , , - , Tomcat webapps/ROOT.

+6

-

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

, , URL-,

static/images/a.gif
../static/images/a.gif
+2

Source: https://habr.com/ru/post/1793594/


All Articles