gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:27:45 26 4
gpt4 key购买 nike

我对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com