`
coffee_yan
  • 浏览: 35490 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Servlet中/和/*的区别

阅读更多
转自一位国外哥们儿写的分析,写的很不错:
Let's consider this servlet mapping in web.xml that defines "App" as the default servlet:

 <servlet-mapping>
 <servlet-name>App</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>

Now call http://server/context/path/to/test.html. Here are the request properties:
getPathInfo() : null
getServletPath() : "/path/to/test.html"
Why is path info null, and why does the servlet path have what we could have expected to see in path info?

Let's change web.xml like this, so that "App" eats the same URLs but is no more the default servlet:

 <servlet-mapping>
 <servlet-name>App</servlet-name>
 <url-pattern>/*</url-pattern>
 </servlet-mapping>

And call again the same http://server/context/path/to/test.html:
getPathInfo() : "/path/to/test.html"
getServletPath() : "" (empty string)
WTF? Is it a bug in the servlet engine? Let's check the servlet specification...

In the "Mapping request to servlets" chapter, the specification of mappings is described:
A string beginning with a ‘/’ character and ending with a ‘/*’ postfix 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.
When writing the "/" mapping, we use rule 3, whereas when using the "/*" mapping, we use rule 1.

So that means that a servlet that needs to map a resource according to the request URL must behave differently depending on whether it is defined as the default servlet or mounted to a particular location. What's the reason for this?
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics