單獨說一下request.getPathInfo() 方法的作用:
request.getPathInfo();
這個方法返回請求的實際URL相對於請求的serlvet的url的路徑。(個人理解。)
比如,有一個Servlet的映射是這樣配置的:
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/servlet/test/*</url-pattern>
</servlet-mapping>
為servlet配置的訪問路徑是:/servlet/test/*
我只要訪問:
http://localhost:8080/dwr/servlet/test/%E8%BF%99%E9%87%8C%E5%8F%AF%E4%BB%A5%E6%98%AF%E4%BB%BB%E4%BD%95%E4%B8%9C%E8%A5%BF
就可以訪問那個servlet。上面url中的dwr 是項目的名字
比如,我用這個 URL 來訪問它:
http://localhost:8080/dwr/servlet/test/joejoe1991/a.html
這個實際的URL,相對於那個servlet 的url ("/servlet/test/*")的路徑是:/joejoe1991/a.html
所以 request.getPathInfo() 方法返回的就是:"/joejoe1991/a.html"
如果你的URL里有查詢字符串,getPathInfo() 方法並不返回這些查詢字符串。
例如:
http://localhost:8080/dwr/servlet/test/joejoe1991/a.html?name=test
getPathInfo() 返回的仍然是:"/joejoe1991/a.html" ,而並不包括后面的"?name=test"
我們可以利用這個方法去做類似於多用戶博客系統的那種URL。
都是http://www.xxx.com/blog/ 開頭,后面跟的是用戶名,比如我要訪問joejoe1991的博客:
http://www.xxx.com/blog/joejoe1991
這個joejoe1991並不是一個真實存在的目錄。
建一個servlet,配置路徑為:/blog/*
然后在這個servlet里調用request.getPathInfo() 方法。
比如:http://www.xxx.com/blog/jjx
那request.getPathInfo() 方法返回的就是jjx ,表示要訪問jjx的博客。
這時再去數據庫里查相應的數據就好。
http://www.xxx.com/1.html 上點連接到 http://www.xxx.com/2.html 上
http://www.xxx.com/2.html%E7%9A%84Referer%E5%B0%B1%E6%98%AFhttp://www.xxx.com/1.html