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 ?
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.
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.
Thanks !
You can do it with HttpServletRequest . I suggest you review the methods of 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()
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.