如何获取JAVA中浏览器地址栏中显示的URL?

问题描述 投票:0回答:1

我搜索了很多次,并且在互联网上没有明确的答案:我可以获得与Java浏览器地址栏中显示的URL完全相同的URL,如果是,如何?

我的意思是确切的地址:对我而言,它将是“https://stackoverflow.com/questions/ask”,或“https://stackoverflow.com/questions/54790941/how-to-get-the-url-as-shown-in-browsers-address -bar-in-java“(没有:和/之间的空格)这篇文章。

我知道我不能拥有“#...”,因为这不是由浏览器传输的,所以这应该是一个例外。

为了简化这一点,我想在JavaScript中使用“window.location.href”。

谢谢 !

java url browser
1个回答
0
投票

你可以用HttpServletRequest做到这一点。我建议你查看HttpServletRequest的方法。

例如:

private String getBaseUrl(HttpServletRequest httpServletRequest) {
    final String scheme =   httpServletRequest.getScheme() + "://";  // http://
    final String serverName = httpServletRequest.getServerName();  // /example.com
    final String serverPort = (httpServletRequest.getServerPort() == 80) ? "" : ":" + httpServletRequest.getServerPort(); // 80 or ?
    final String contextPath = httpServletRequest.getContextPath(); // /webapp
    final String servletPath = httpServletRequest.getServletPath(); // /test/test
    return scheme + serverName + serverPort + contextPath + servletPath;
}

结合getRequestURL()getQueryString()的结果

private String getUrl(HttpServletRequest httpServletRequest) {
    final StringBuffer requestUrl = httpServletRequest.getRequestURL();
    final String queryString = httpServletRequest.getQueryString();
    if (queryString != null) {
        requestUrl.append('?');
        requestUrl.append(queryString);
    }
    return requestUrl.toString();
}
© www.soinside.com 2019 - 2024. All rights reserved.