Getting request URL in servlet

I want to know the difference between the two ways to get the request URL in a servlet.

Method 1:

String url = request.getRequestURL().toString(); 

Method 2:

 url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI(); 

Is there any chance that the two above methods will give two different URLs?

+43
java servlets
Oct 28 2018-10-10T00:
source share
1 answer

getRequestURL() omits the port when it is 80, while the http scheme or when it is 443, while the https scheme.

So just use getRequestURL() if all you need is to get the whole URL. However, this does not include the GET request string. You can build it like this:

 StringBuffer requestURL = request.getRequestURL(); if (request.getQueryString() != null) { requestURL.append("?").append(request.getQueryString()); } String completeURL = requestURL.toString(); 
+65
Dec 10 '10 at 19:25
source share
β€” -



All Articles