Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get domain name in url with JSTL?

Tags:

java

url

jsp

jstl

el

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

When I do:

${pageContext.request.remoteHost}

I get my server's IP.

When I do:

${pageContext.request.serverName}

I normally get the right domain name, but on a server we have on amazon its returning "server1" instead of 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?

like image 792
UpHelix Avatar asked Sep 27 '10 17:09

UpHelix


3 Answers

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.

like image 88
BalusC Avatar answered Nov 10 '22 22:11

BalusC


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();
    }
like image 20
jmj Avatar answered Nov 10 '22 22:11

jmj


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 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.

like image 37
matt b Avatar answered Nov 10 '22 22:11

matt b