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

时间:2019-02-20 16:21:14

标签: java url browser

我搜索了很多次,但在Internet上搜索结果却不明确:我能否获得与Java Web浏览器地址栏中显示的URL完全相同的网址,如果可以,如何获取?

我的意思是确切的地址:对于我来说,现在是“ https://stackoverflow.com/questions/ask”或“ https://stackoverflow.com/questions/54790941/how-to-get-the-url-as-此帖子的“显示在浏览器中的地址栏在Java中”(在:和/之间没有空格)。

我知道我无法使用“#...”,因为它不是由浏览器传输的,因此这应该是一个例外。

为简单起见,我希望确切的东西在JavaScript中具有“ window.location.href”。

谢谢!

1 个答案:

答案 0 :(得分: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();
}