在 Spring MVC 中的 servlet 映射中,如何映射 url 模式目录的根? [英] In a servlet mapping in Spring MVC how do I map the root of a url pattern directory?
问题描述
<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 映射:
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).
推荐答案
Yevgeniy 是正确的,但如果您的 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 模式目录的根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!