Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting request URL in a servlet

Tags:

java

servlets

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?

like image 940
selvam Avatar asked Oct 28 '10 05:10

selvam


People also ask

What is a request URL?

A request URL consists of an HTTP method, a base URL, and a resource URI. The request header also includes parameters such as the content type and authorization information.

How a GET request is processed by a servlet?

When a request comes in for a servlet, the server hands the request to the Web Container. Web Container is responsible for instantiating the servlet or creating a new thread to handle the request. Its the job of Web Container to get the request and response to the servlet.


1 Answers

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();
like image 125
BalusC Avatar answered Oct 24 '22 06:10

BalusC