java - Spring MVC Servlet映射, "/xxx"和 "/xxx/*"之间的区别

标签 java spring-mvc servlet-mapping

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

当'getServletMappings'返回“/”时,我可以得到正确的响应“http://localhost:8080/hello”。

但如果我将其更改为“/app”并将 url 更改为“http://localhost:8080/app/hello”,则不起作用,它会返回 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 容器仅在存在完全匹配时才将请求路由到它,这意味着仅当您将网址更改为“http://localhost:8080/app ”。这就没有空间添加额外的路径来定位特定的 Spring Controller (更准确地说:如果您使用 @RequestMapping("/app ") 因为 DispatcherServlet 会回退到使用整个 url 进行搜索,但实际上这不是您想要的)。

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

关于java - Spring MVC Servlet映射, "/xxx"和 "/xxx/*"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58206930/

相关文章:

java - 在 c3p0 池中检查连接

tomcat - java.lang.IllegalArgumentException : Invalid <url-pattern> SolrServlet1 in servlet mapping

maven - 带有依赖项的pom.xml中的错误(缺少 Artifact ……)

java - 审计模型中的属性变化

java - 无法在 Spring 中获取自定义注释以在 Spock 集成测试中工作

tomcat - servlet 映射错误和/或 Tomcat 服务器本地主机未运行

java - 过滤器映射到最后一个路径段

SQLite 中的 Java PreparedStatement.executeBatch() 不工作

java - 在 driver=new ChromeDriver(); 行上获取 "InvocationTargetException"异常;

java - 异步执行多个任务并在 JavaScript 函数中返回第一个成功的结果