2012-06-01 97 views
4

我正在處理捕獲當前URL,因爲它顯示在我的JSP頁面的瀏覽器地址欄中,並且沒有多少選項可以完成它。在Web應用程序中獲取當前URL

在我當前的應用程序中,我們打算將Web服務器放在我們的應用程序服務器前,因爲這些值似乎沒有任何用處。

我有另一種方法來接受javascript的document.URL的幫助,但我不確定它將會如何可靠。

我需要獲取有關用戶位置的詳細信息,如果我可以使用getRequestURI(),它會返回類似www.abc.com/abc/search.jsp的東西。

總之,我想捕獲瀏覽器地址欄中存在的URL,並將其保存在JSP頁面的隱藏字段中。

我不確定實現這一目標的最佳方法是什麼。

+1

你想要的 「關於用戶的位置」 getRequestURI()和。問題不是很清楚。你可以簡化你想要的東西嗎? –

+1

所有我想要捕獲瀏覽器地址欄中存在的URL並將其保存在我的JSP頁面的隱藏字段中 –

+0

在jsp中寫入getRequestURI()。這應該是正確的。 –

回答

3

如果你想要一個JavaScript的解決方案,你可以使用window.document.location對象及其屬性:

console.log(window.document.location.protocol); 
http: 
console.log(window.document.location.host); 
stackoverflow.com 
console.log(window.document.location.port); 

console.log(window.document.location.href); 
http://stackoverflow.com/questions/10845606/get-current-url-in-webapplication 
console.log(window.document.location.pathname); 
/questions/10845606/get-current-url-in-webapplication 

您可以瞭解其他參數的MDN閱讀this article

+0

感謝您的輸入,我正在解決基於JavaScript的solution.i有一個問題'window.document.location.pathname'將選擇查詢字符串,如果任何附加到URL? –

+0

不是,那是location.search位。查看我添加到我的答案的鏈接。 – Zlatko

+0

謝謝,我爲我工作:) –

2

您可以在表單中創建一個隱藏字段

<input type="hidden" id="myurl" name="myurl"/> 

然後寫一個javascript

<script type="text/javascript"> 
document.getElementById('myurl').value = window.location.href 
</script> 

是幫助嗎?

4

在Java中,你可以這樣做:

public static String getCurrentUrl(HttpServletRequest request){ 

    URL url = new URL(request.getRequestURL().toString()) 

    String host = url.getHost(); 
    String userInfo = url.getUserInfo(); 
    String scheme = url.getProtocol(); 
    String port = url.getPort(); 
    String path = request.getAttribute("javax.servlet.forward.request_uri"); 
    String query = request.getAttribute("javax.servlet.forward.query_string"); 
    URI uri = new URI(scheme,userInfo,host,port,path,query,null) 
    return uri.toString(); 
}