Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

java - 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>

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 = {"","/"})

EDIT:

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;
    }
}

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 = {"","/"})

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","/"})

However, now the URL /admin/users/users will also work (which is not what I would want).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...