Hi,
I'm developing a Spring MVC app using Spring Boot 2.4.1.
I add the following configurations to application.properties
in order to switch path matching strategy to the new PathPatternParser
:
spring.mvc.pathmatch.matching-strategy=path_pattern_parser
But after that access to the root path (/) won't be redirected to /index.html
. Access the full path http://xxxxx/index.html
is OK. If switching back to AntPathMatcher
, redirect works normally.
PS: I set spring.web.resources.static-locations
to a local directory which contains static resources.
Comment From: samotoo
Hi,
By tracking down the code I find something relates to the issue.
In ResourceHttpRequestHandler.java
(spring-webmvc 5.3.2):
...
protected Resource getResource(HttpServletRequest request) throws IOException {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
if (path == null) {
throw new IllegalStateException("Required request attribute '" +
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE + "' is not set");
}
path = processPath(path);
if (!StringUtils.hasText(path) || isInvalidPath(path)) {
return null;
}
...
The path
variable is get from request attribute HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE
,if using AntPathMatcher
, it can get the correct path (index.html in this case), but using PathPatternParser
, path is an empty string. And later StringUtils.hasText(path)
returns false causes the method returning null. Then 404 is returned to the client.
Hope this helps.
Comment From: snicoll
@samotoo thanks for the report, I was able to reproduce the issue (simple app from start.spring.io with an index.html
in src/main/resources/static
).
In both cases our WelcomePageHandlerMapping
is registering the welcome page:
INFO 78870 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
Based on your analysis I can see indeed two code paths where, with AntPathMatcher
the pathWithinMapping
is index.html
(see AbstractUrlHandlerMapping#lookupHandler
, whereas the PathPatternMatcher
provides a pathWithinMapping
of ` (empty string), see the new
AbstractUrlHandlerMapping#lookupHandler` introduced in Spring Framework 5.3.
At this point, I'd like the framework team to review the use case so I am going to move this issue there.
Comment From: rstoyanchev
For PathPattern
, the DispatcherServlet
determines the RequestPath
once per request and cache it in a request attribute. The welcome page comes in as "/" initially and results in a forward to "/index.html" but on the forward we don't update the RequestPath
and it remains as "/".