I want to know the difference between the below two methods of getting a request URL in servlet.
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?
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is 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:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
Source: Stackoverflow.com