<script type="text/javascript"> thisURL = document.URL; thisHREF = document.location.href; thisSLoc = self.location.href; thisDLoc = document.location; strwrite = " thisURL: [" + thisURL + "]<br />" strwrite += " thisHREF: [" + thisHREF + "]<br />" strwrite += " thisSLoc: [" + thisSLoc + "]<br />" strwrite += " thisDLoc: [" + thisDLoc + "]<br />" document.write( strwrite );
thisTLoc = top.location.href; thisPLoc = parent.document.location; thisTHost = top.location.hostname; thisHost = location.hostname; strwrite = " thisTLoc: [" + thisTLoc + "]<br />" strwrite += " thisPLoc: [" + thisPLoc + "]<br />" strwrite += " thisTHost: [" + thisTHost + "]<br />" strwrite += " thisHost: [" + thisHost + "]<br />" document.write( strwrite );
若頁面不在框架中,top 與 parent 都等於自己,因此這幾行的值會相同。跨域框架情況下,存取上層的 location 會因同源策略而拋出錯誤。
tmpHPage = thisHREF.split( "/" ); thisHPage = tmpHPage[ tmpHPage.length - 1 ]; tmpUPage = thisURL.split( "/" ); thisUPage = tmpUPage[ tmpUPage.length - 1 ]; strwrite = " thisHPage: [" + thisHPage + "]<br />" strwrite += " thisUPage: [" + thisUPage + "]<br />" document.write( strwrite );
以斜線切分後取最後一段,就是檔名。若網址帶有查詢字串或 hash,檔名會包含這些部分,需另行處理。
var url = "<%=request.getRequestURI()%>"; alert(url)
JSP 提供的相關方法:
request.getRequestURI():請求的 URI 路徑,不含協定、主機與埠,也不含查詢字串。request.getRequestURL():完整的請求 URL(含協定、主機、埠、路徑),不含查詢字串。request.getQueryString():查詢字串部分(問號後面那一段)。request.getServletPath():對應到 servlet 的路徑部分。若要組出完整的網路位址,可拼接:
request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI()
純前端需求(例如取得目前頁面檔名做為標題)用 location.pathname 或 document.URL 即可;需要伺服器已知的部署路徑(context path)時,用 request.getContextPath() 會比的字串拼接更可靠,尤其當應用程式被部署到非根路徑時。另注意反向代理或 HTTPS 卸載的環境下,getScheme() 與 getServerPort() 回傳的可能是內部值,需配合 X-Forwarded-* 標頭判斷。