在Webapplication中获取当前URL

Ume*_*thi 5 javascript java jsp java-ee

我正在捕获当前URL,因为它显示在我的JSP页面的浏览器地址栏中,并且没有多少选项可以完成它.

在我目前的应用程序中,我们将把web服务器放在我们的应用程序服务器前面,而不是看起来这些值没有任何用处.

我有另一种方式来获取javascript的帮助, document.URL但我不确定它会有多可靠.

我需要获取有关用户位置的详细信息,如果我可以使用getRequestURI(),它将返回类似的内容www.abc.com/abc/search.jsp.

简而言之,我只想捕获浏览器地址栏中的URL,并将其保存在JSP页面的隐藏字段中.

我不确定实现这一目标的最佳方法是什么.

小智 6

在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();
}
Run Code Online (Sandbox Code Playgroud)


Zla*_*tko 4

如果你想要一个 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
Run Code Online (Sandbox Code Playgroud)

您可以阅读MDN 上的这篇文章来了解其他参数。