繁体   English   中英

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

[英]How to get the URL as shown in browser's address bar in JAVA?

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

我的意思是确切的地址:对我而言,现在是“ https://stackoverflow.com/questions/ask ”或“ https://stackoverflow.com/questions/54790941/how-to-get-the-url -如在浏览器中显示的地址栏在Java中”(在此和之间不带空格)。

我知道我不能使用“#...”,因为这不是由浏览器发送的,因此这应该是一个例外。

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

谢谢 !

您可以使用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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM