A servlet mapping tells the servlet container which request should be handled by the given servlet. Here is an example servlet mapping for Spring’s DispatcherServlet:
<servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
The referenced servlet (called mvc-dispatcher) is defined in a <servlet>
tag like this:
<servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
Possible URL patterns
There are four cases of pattern usage:
- A string beginning with a
*.
prefix is used as an extension mapping. It matches all requests that have the specified extension. - A string beginning with a
/
character and ending with a/*
suffix is used for path mapping. It matches all request that begin with a given path (e.g. /home/* matches /home/welcome, /home/contact…) - A string containing only the
/
character indicates the “default” servlet of the application. - All other strings are used for exact matches only.
How mapping happens?
The first successful match is used with no further attempts. The following steps happen in the order listed here:
- The container tries to find an exact match. If a match is found that servlet is selected for handling the request.
- The container tries to recursively match on the longest path prefix. The longest match determines the servlet selected.
- If the last segment of the url contains an extension (e.g. .jsp) the container tries to find a servlet which handles that specific extension.
- If neither of the previous three rules result in a match, the container will try to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.
Difference between / and /* in servlet mapping
Mixing up these two mappings can cause a lot of headaches and unexpected behaivour, so it’s important to know the differences:
- The patternĀ
/
will make your servlet the default servlet for the app, meaning it will pick up every pattern that doesn’t have another exact match. - The pattern
/*
will force everything through your servlet. In essence, every request goes through this servlet even requests for JSPs. This causes JSPs not to work. Usually it’s best to avoid this pattern.