【问题标题】:Get current URL in Webapplication在 Web 应用程序中获取当前 URL
【发布时间】:2012-06-06 10:03:18
【问题描述】:

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

在我当前的应用程序中,我们将把 web-server 放在我们的应用程序服务器前面,因为这些值似乎没有任何用处。

我还有另一种方法可以帮助 javascript 的 document.URL,但我不确定它的可靠性。

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

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

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

【问题讨论】:

  • 你想要“关于用户的位置”和 getRequestURI()。问题不是很清楚。你能把你想要的简单化吗?
  • 所有我想捕获浏览器地址栏中的 URL 并将其保存在我的 JSP 页面的隐藏字段中
  • 在jsp中写入getRequestURI()。那应该是正确的。

标签: java javascript jsp jakarta-ee


【解决方案1】:

在 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();
}

【讨论】:

    【解决方案2】:

    如果你想要一个 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了解其他参数。

    【讨论】:

    • 感谢您的输入,我正在解决基于 javascript 的解决方案。我有一个问题,window.document.location.pathname 将选择查询字符串(如果有任何附加到 URL)?
    • 不,那是 location.search 位。查看我添加到答案中的链接。
    【解决方案3】:

    您可以在表单中创建隐藏字段

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

    然后写一个javascript

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

    有帮助吗?

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多