开发者

Get domain name in url with JSTL?

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开发者_StackOverflow中文版.

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?


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.


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();
    }


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.


${pageContext.request.contextPath}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜