gpt4 book ai didi

java - Spring mvc servlet url 未正确映射

转载 作者:行者123 更新时间:2023-12-02 03:16:59 25 4
gpt4 key购买 nike

当我转到第一个网址时,它会调用 Controller 中的 home() 方法,但当我转到第二个网址时,它不会调用我的 homeTest() 方法。这是为什么?

我收到 404 错误。

http://localhost:9083/MYAPP/foo       ------ first url
http://localhost:9083/MYAPP/foo/bar ------ second url

web.xml

<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/foo/*</url-pattern>
</servlet-mapping>

Controller :

@RequestMapping(value="/foo", method = RequestMethod.GET)
public String home(Model model){
return "home";
}

@RequestMapping(value="/foo/bar", method = RequestMethod.GET)
public String homeTest(Model model){
return "home";
}

最佳答案

您需要配置您的RequestMappingHandlerMapping .

官方文档详细介绍了handler mappings以及他们的一些属性(property)。这里相关的是 alwaysUseFullPath :

  • alwaysUseFullPath If true, Spring uses the full path within the current Servlet context to find an appropriate handler. If false (the default), the path within the current Servlet mapping is used. For example, if a Servlet is mapped using /testing/* and the alwaysUseFullPath property is set to true, /testing/viewPage.html is used, whereas if the property is set to false, /viewPage.html is used

简而言之,当尝试查找 /foo/bar 的映射时,它会删除与 Servlet 环境匹配的部分,即 /foo,并且只删除使用 /bar 查找处理程序。您没有映射到 /bar 的处理程序。

通过将上述属性设置为 true,它将使用完整路径。

您可以在注释为 WebMvcConfigurationSupport@Configuration 中进行配置。子类,通过覆盖 requestMappingHandlerMapping

@Override
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
handlerMapping.setAlwaysUseFullPath(true);
return handlerMapping;
}

或者任何适合您的配置的机制(例如,有一个 XML 等效项)。

<小时/>

/foo 的精确匹配有一种特殊情况。在这里并不是特别相关。

关于java - Spring mvc servlet url 未正确映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40162345/

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