Spring MVC Servlet 映射,“/xxx”和“/xxx/*”之间的区别

Spring MVC Servlet Mapping, differences between "/xxx" and "/xxx/*"

我对 Spring MVC 的 url 模式映射的工作方式感到困惑。

当'getServletMappings' returns "/"时,我可以用"http://localhost:8080/hello"得到正确的响应。

但如果我将其更改为“/app”并将 url 更改为“http://localhost:8080/app/hello”,则无法正常工作,它 returns 404 错误。

我是不是误会了什么,我也发现“/app/*”可以工作(我能理解这一点),但为什么“/app”不能?

请检查我的代码:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected String[] getServletMappings() {
        // works with http://localhost:8080/hello
        return new String[] {
                "/"
        };
        // NOT working with http://localhost:8080/app/hello
        // return new String[] {
        //      "/app"
        //};
    }
}



@RestController
public class HTTPMethodsController {
   @RequestMapping("/hello")
   public String hello() {
       return "Hello SpringMVC.";
   }
}

根据Servlet specification Chapter 12.2,servlet 的映射必须使用以下语法:

  • A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
  • A string beginning with a ‘*.’ prefix is used as an extension mapping.
  • The empty string ("") is a special URL pattern that exactly maps to the application's context root, i.e., requests of the form application's context root, i.e., requests of the form http://host:port//. In this case the path info is ’/’ and the servlet path and context path is empty string (““).
  • A string containing only the ’/’ character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  • All other strings are used for exact matches only.

因此,将 DispatcherServlet 映射到 URL "/app",会导致 servlet 容器仅在完全匹配时将请求路由到它,这意味着仅当您更改url 到“http://localhost:8080/app”。这没有为目标特定 Spring 控制器添加额外路径的余地(更准确地说:如果你使用 @RequestMapping("/app") 映射它,你实际上可以点击你的 hello() 控制器方法,因为 DispatcherServlet 回退到搜索整个 url,但实际上这不是您想要的)。

因此映射“/app/*”是正确的,或者您也可以将其映射为带有“/”的默认 servlet,如您所见。