J.Joe J.Joe - 1 month ago 14
Java Question

About Spring MVC can't resolve static resource in the WEB-INF

My WEB structure like this :
enter image description here

My Spring-MVC config like this :

<mvc:resources location="/WEB-INF/static/" mapping="/static/**" />


And my servlet config like this :

<!-- Servlet Dispatcher -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/SpringMVC.xml</param-value>
</init-param>
<!-- 配置启动延时 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>


When config like that the web project can't resolve the static resrouce , but if i change the url-pattern to '/'

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


The web can resolve it .

I want to know why and there are other way to resolve the static resource if the url-pattern is not the '/' , thanks (●'◡'●)

Answer

If you are using suffix mapping (*.something), then Spring uses just the first part (without the suffix). This is interpreted by spring as just /index in your url-pattern (without the suffix).

And hence you get 404.

Please find the documentation of Spring UrlPathHelper#getPathWithinServletMapping for better description what is being used in the mapping process:

To fix your problem in the current servlet mapping

servlet mapping = "/*.html"; request URI pattern = "/a.html"

Comments