There seems to be a bug in MvcUriComponentsBuilder, so I fixed it.

affects

  • Spring 5.2.1 and older.
  • Using Spring WebMVC and JSP/Thymeleaf.

problem

MvcUriComponentsBuilder generates incorrect URLs from paths without slashes.

  • Context Path

/demo

  • Controller
@Controller
@RequestMapping("test") // non slash path
public class TestController {

    @GetMapping
    public String test() {
        return "test";
    }
}
  • JSP (The same problem will happen with Thymeleaf)
<a href="${spring:mvcUrl('TC#test').build()}">test</a>
  • Created HTML
<a href="/demotest">test</a>
<!-- expected '/demo/test' -->

Cause

At MvcUriComponentsBuilder#fromMethodInternal, PathMatcher adds a slash between the path of class @RequestMapping and the path of method @RequestMapping. However, no slash is added at the beginning of the merged path.