Java 在 servlet 中获取请求 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4040094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting request URL in a servlet
提问by selvam
I want to know the difference between the below two methods of getting a request URL in servlet.
我想知道以下两种在 servlet 中获取请求 URL 的方法之间的区别。
Method 1:
方法一:
String url = request.getRequestURL().toString();
Method 2:
方法二:
url = request.getScheme()
+ "://"
+ request.getServerName()
+ ":"
+ request.getServerPort()
+ request.getRequestURI();
Are there any chances that the above two methods will give two different URLs?
上述两种方法是否有可能给出两个不同的 URL?
回答by BalusC
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
的getRequestURL()
,当它为80,而方案是省略了端口http
,或当它是443,而方案https
。
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
因此,getRequestURL()
如果您想要的只是获取整个 URL,请使用。但是,这不包括 GET 查询字符串。您可能希望按如下方式构建它:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();