[英]Getting request URL in a servlet
I want to know the difference between the below two methods of getting a request URL in servlet. 我想知道以下两种在servlet中获取请求URL的方法之间的区别。
Method 1: 方法1:
String url = request.getRequestURL().toString();
Method 2: 方法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?
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()
在方案为http
时为80时忽略端口,在方案为https
时为443时省略。
So, just use getRequestURL()
if all you want is obtaining the entire URL. 所以,如果你想要的只是获取整个URL,只需使用getRequestURL()
。 This does however not include the GET query string. 但这不包括GET查询字符串。 You may want to construct it as follows then: 您可能希望按如下方式构造它:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.