简体   繁体   English

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

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

I searched for this many times and their is no clear answer for it on the Internet : can I get the URL exactly as it appears in web browser's address bar in Java and, if yes, how ? 我搜索了很多遍,但在Internet上却找不到明确的答案:我能否获得与Java Web浏览器地址栏中显示的URL完全相同的URL,如果可以,该如何获得?

I mean the exact address : for me now, it would be " https://stackoverflow.com/questions/ask ", or "https: //stackoverflow.com/questions/54790941/how-to-get-the-url-as-shown-in-browsers-address-bar-in-java" (without the space between : and /) for this post. 我的意思是确切的地址:对我而言,现在是“ https://stackoverflow.com/questions/ask ”或“ https://stackoverflow.com/questions/54790941/how-to-get-the-url -如在浏览器中显示的地址栏在Java中”(在此和之间不带空格)。

I know that I can't have the "#..." because this is not transmitted by the browser, so this should be an exception. 我知道我不能使用“#...”,因为这不是由浏览器发送的,因此这应该是一个例外。

To make this simple, I would like to have the exact thing has the "window.location.href" in JavaScript. 为简单起见,我希望确切的东西在JavaScript中具有“ window.location.href”。

Thanks ! 谢谢 !

You can do it with HttpServletRequest . 您可以使用HttpServletRequest做到这一点。 I suggest you review the methods of HttpServletRequest. 我建议您回顾一下HttpServletRequest的方法。

For example: 例如:

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;
}

Combining the results of getRequestURL() and getQueryString() 合并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