写web.xml时servlet-mapping都是随意些,终于遇到了问题,研究下
How is servlet mapping defined?
servlet映射是如何定义的?
Servlets should be registered with servlet container. For that, you should add entries in web deployment descriptor web.xml. It is located in WEB-INF directory of the web application.
Entries to be done in web.xml for servlet-mapping:
servlets应该被注册在servlet容器中,为了达到这个目的,需要在web部署描述符web.xml中添加servlets。它位于WEB-INF目录,下面是映射需要的组件:
<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.
servlet-mapping有两个子标签,url-pattern和servlet-name,url-pattern定义哪些url需要调用servlet-name中定义的servlet,url比较是区分大小写的。
Syntax for servlet mapping as per servlet specification SRV.11.2:
SRV.11.2规范中定义的映射语法:
A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
A string containing only the ‘/’ character indicates the “default” servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
All other strings are used for exact matches only.
以'/'开头,‘/*’结尾的字符串
以‘*.’开头的字符串
‘/’表示默认servlet
其他字符串都用于精确匹配
(注:/**/*.action是非法的,看了这个才明白)
Rule for URL path mapping:
URL路径映射的规则:
It is used in the following order. First successful match is used with no further attempts.
使用下面的顺序,第一个匹配后不再继续
1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.
1. 精确匹配
2. 尽量匹配最长的前缀
3. 如果url包含扩展(例如.jsp),容器会寻找处理这个扩展的servlet,扩展是url最后一段的.之后的字符
4. 如果前三个没有匹配,寻找适合的内容,如果定义了默认servlet,会使用它。