本文介绍了从请求中获取根域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的URL为例。



example.com作为输出。我知道有一个方法 servletrequest.getServerName()。它为我输出 test1.example.com



任何帮助表示感谢。

解决方案

在,您可以使用以下方法获取URI的各个部分。您也可以使用它们逐个重建URL(以帮助调试或其他任务),如下所示:

  / /示例: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&年龄= 30

所以是最接近的我们得到你需要。



根域:



对于根域,你将不得不处理从 getServer返回的 String 名称()。这是必要的,因为Servlet无法提前知道你所谓的主机或者只是像 .com 这样的域(它可能是一台名为网络中的 com - 而不仅仅是后缀 - 谁知道?)。



对于您提供的模式(三分之一+二级+ com / net),以下内容应该得到你所需要的:

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

以上将给出以下输入/输出:

  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


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.

解决方案

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

这篇关于从请求中获取根域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 15:08
查看更多