tags:

views:

90

answers:

3

I am trying to get the domain name from the url with JSTL. The 2 methods I know return the wrong info. I need exactly what is in the url.

When I do: ${pageContext.request.remoteHost} I get an IP. When I do ${pageContext.request.serverName} I normally get the right domain name but on a server we have on amazon it is returning "server1" instead if the correct domain name, probably because of the way it handles multiple domains. Anyone know how I can get the current domain name in the url?

I may need to get the url and then parse it. How would I do that?

+1  A: 

You can parse domain name from URL

OR

 public static String getDomainName(String url)
    {
         URL u;
         try {
             u = new URL(url);
         } 
         catch (Exception e) { 
             return "";
         }
         return u.getHost();
    }
org.life.java
Okay, that's what I need to know how to do. I might need better explain my question. How do I get the url, and parse it?
Dale
@Dale updated..
org.life.java
+1  A: 

You can use HttpServletRequest.getRequestUrl() to:

Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters.

this would return a String like http://stackoverflow.com/questions/3806045/get-domain-name-in-url-with-jstl

It should then be trivial to parse this to find the string that comes after the scheme (http, https, etc) and before the requestURI.

matt b
A: 

You should be using ServletRequest#getLocalName() instead. It returns the real hostname of the server. The ServletRequest#getServerName() indeed returns the value as set in Host header.

${pageContext.request.localName}

That's all. The solutions suggested in other answers are plain clumsy and hacky.


By the way, the ServletRequest#getRemoteHost() doesn't return the server's hostname, but the client's one (or the IP when the hostname is not immediately resolveable). It's obviously the same as the server's one whenever you run both the webserver and webbrowser at physically the same machine. If you're interested in the server's IP, use ServletRequest#getLocalAddr(). The terms "local" and "remote" must be interpreted from server's perspective, not from the client's. It's after all the server there where all that Java code runs.

BalusC