51

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?

1 Answer 1

80

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.