Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

java - Get root domain from request

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.

question from:https://stackoverflow.com/questions/17241532/get-root-domain-from-request

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

// Example: http://myhost:8080/people?lastname=Fox&age=30

String uri = request.getScheme() + "://" +   // "http" + "://
             request.getServerName() +       // "myhost"
             ":" + request.getServerPort() + // ":" + "8080"
             request.getRequestURI() +       // "/people"
            (request.getQueryString() != null ? "?" +
             request.getQueryString() : ""); // "?" + "lastname=Fox&age=30"

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 from getServerName(). 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 called com 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:

String domain = request.getServerName().replaceAll(".*\.(?=.*\.)", "");

The above will give the following input/outputs:

www.test.com       -> test.com
test1.example.com  -> example.com
a.b.c.d.e.f.g.com  -> g.com
www.com            -> www.com
com                -> com

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...