Get URL Base / Hostname of the servlet

Here is a simple method for getting hostname of the current servlet:

public String getUrlBase(HttpServletRequest request) 
        throws MalformedURLException {
    URL requestUrl = new URL(request.getRequestURL().toString());
    String portString = 
            requestUrl.getPort() == -1 ? "" : ":" + requestUrl.getPort();
    return requestUrl.getProtocol() + 
            "://" + requestUrl.getHost() + portString + "/";
}
Advertisements
This entry was posted in Java and tagged , . Bookmark the permalink.

2 Responses to Get URL Base / Hostname of the servlet

  1. Darshan says:

    thanks.. Worked like a charm…. Much appreciated

  2. eugene says:

    very nice solution!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s