Consider the below URL as an example. http://www.test1.example.com
Is there any method by which I can get "example.com" as an output. I know there is a method servletrequest.getServerName()
. It gives me output as test1.example.com
Any help appreciated.
Hope this helps.
You can do this as a simple String manipulation:
There is no standard way obtain
example.com
froma.b.c.example.com
because such a transformation is generally not useful. There are TLDs that don't allow registrations on the second level; for example all.uk
domains. Givennews.bbc.co.uk
you'd want to end up withbbc.co.uk
, right?In
HttpServletRequest
, you can get individual parts of the URI using the methods below. You could also use them to reconstruct the URL piece by piece (to help debugging, or other tasks), like this:So
request.getServerName()
is the closest we got to you need.The "root domain":
For the "root domain", you'll have to work through the
String
returned fromgetServerName()
. This is necessary because the Servlet would have no way of knowing ahead of time what you call "host" or what is just a domain like.com
(it could be a machine calledcom
in your network - and not just a suffix -, who knows?).For the pattern you gave (one third+secondlevel+com/net), the following should get what you need:
The above will give the following input/outputs:
We have more reliable way of doing the same. There is google library "guava". Add following dependency in your pom.
Then try
This will give you
"example.co.in"