Servlet中/和/*的区别

本文通过对比两种不同的Servlet映射方式(默认映射与通配符映射),深入探讨了getPathInfo()与getServletPath()在不同场景下的表现差异,并结合Servlet规范解释了这种行为的原因。
[size=medium]转自一位国外哥们儿写的分析,写的很不错:
Let's consider this servlet mapping in web.xml that defines "App" as the default servlet:
[/size]
 <servlet-mapping>
<servlet-name>App</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

[size=medium]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:[/size]
 <servlet-mapping>
<servlet-name>App</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

[size=medium]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?[/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值