问题描述
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
如果我点击 / test / page ,以上操作就可以了。但是,点击 / test 或 / test / 将无效。我正在使用Spring MVC,我的请求映射如下:
If I hit /test/page the above will work. However, hitting /test or /test/ will not work. I'm using Spring MVC, and my request mapping is as follows:
@RequestMapping(value = {"","/"})
编辑:
我正在使用独立项目进行验证,但这似乎是Spring的UrlPathHelper的错误。当存在上下文和servlet路径时,以下方法返回不正确的路径,并且在没有尾部斜杠的情况下命中servlet。
I'm in the process of verifying with an independent project, but this appears to be a bug with Spring's UrlPathHelper. The following method returns an incorrect path when there is both a context and a servlet path, and you hit the servlet without a trailing slash.
public String getPathWithinApplication(HttpServletRequest request) {
String contextPath = getContextPath(request);
String requestUri = getRequestUri(request);
if (StringUtils.startsWithIgnoreCase(requestUri, contextPath)) {
// Normal case: URI contains context path.
String path = requestUri.substring(contextPath.length());
return (StringUtils.hasText(path) ? path : "/");
}
else {
// Special case: rather unusual.
return requestUri;
}
}
就像一个例子,假设我有一个上下文admin和以下servlet-mapping:
Just as an example let's say I have a context of "admin" and the following servlet-mapping:
<servlet-mapping>
<servlet-name>usersServlet</servlet-name>
<url-pattern>/users/*</url-pattern>
</servlet-mapping>
现在我在我的一个控制器中有一个请求映射,如下所示:
Now I have a request mapping in one of my controllers like this:
@RequestMapping(value = {"","/"})
如果我点击 / admin / users ,它将无效。但是,如果我点击 / admin / users / ,它就能正常运行。现在,如果我将请求映射更改为以下内容,那么它们都将起作用:
If I hit /admin/users it will not work. However, if I hit /admin/users/ it will work. Now if I change my request mapping to the following then they will both work:
@RequestMapping(value = {"/users","/"})
但是,现在URL / admin / users / users 也可以工作(这不是我想要的)。
However, now the URL /admin/users/users will also work (which is not what I would want).
推荐答案
是正确的,但如果你的DispatcherServlet接管了默认的servlet,你必须将它添加到你的web.xml:
Yevgeniy is correct, but if your DispatcherServlet is taking over for the default servlet, you have to add this to your web.xml:
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
这篇关于在Spring MVC中的servlet映射中,如何映射url模式目录的根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!