How to get root URL of application using HttpServletRequest

In java web application many time we need application root url or base url. We can build server url using HttpServletRequest object as it contains all required information. Below is one sample function to do this.

Example

static final int HTTP_DEF_PORT = 80;
static final int HTTPS_DEF_PORT = 443;
public static String getBaseUrl(HttpServletRequest request) {
if ((request.getServerPort() == HTTP_DEF_PORT) || (request.getServerPort() == HTTPS_DEF_PORT))
return request.getScheme() + "://" + request.getServerName()
+ request.getContextPath();
else
return request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath();
}
public static boolean isNullOrEmpty(String data) {
return (data == null || data.equals(""));
}
}