reset password

Understand Java EE Request Mapping

In Java EE, a request URL is mapped to a servlet based on the following rules. Note that the rules are applied in order, and once a match is found, subsequent rules are not checked.

1. Exact match is based on a servlet mapping specified by <servlet-mapping> in web.xml or using @WebServlet annotation. The URL pattern for an exact match should start with a "/", e.g. /foobar.html.

The  Servlet Specification mentions two special strings: the empty string and "/". Although these two strings do not contain any wild card pattern, they are not used for exact matching. The empty string is supposed to be mapped to the application context root according to the specification, but under Tomcat it will cause a server startup failure regardless of whether it is specified in web.xml or with @WebServlet, so do not use it. "/" is a special pattern used for the default servlet, as described in Rule #6.

2. Prefix match is based on a mapping that starts with "/" and ends with "/*", e.g. /foo/*.

If there are multiple mappings match the same request, the mapping with the longest prefix match is chosen.

3. Suffix match is based on a mapping that begins with "*.", e.g. *.html.

4. Welcome file match only applies to requests for directories, e.g. /foo/bar/. Each file specified in <welcome-file-list> is appended to the request path and a mapping on the new string (original request path + welcome file) is attempted.

5. Implicit match is based on the implicit mappings defined by the servlet container. Tomcat only defines three implicit mappings for JSP (*.jsp and *.jspx), server side includes (*.shtml), and CGI scripts (/cgi-bin/*) . The mappings for the later two are commented out by default.

6. Default servlet. A servlet with the special mapping "/" is called the default servlet. All the requests that do not have a match is mapped to this servlet - in other words, it effectively eliminates 404 error at the servlet mapping level. Note that a 404 error may still occur later, for example, during Spring controller mapping.

One should be careful when using default servlet because an application default servlet overrides the default servlet of the servlet container, which is usually responsible for delivering static resources like images.

7. Error page. If a match cannot be found, an 404 page (either specified in web.xml or a default one) will be displayed.

It is not quite clear from the specification whether the <location> sub-element of <error-page> should be a location on the server (e.g. /WEB-INF/404.jsp) or it could be a URL (e.g. /404.html). Tomcat 7 seems to be fine either way, and in both cases the request is sent to the error page with a forward (or a forward-like mechanism, i.e. not redirect).

This page has been viewed 3216 times.