gpt4 book ai didi

java - java中如何从host文件中获取域名?

转载 作者:行者123 更新时间:2023-12-01 05:27:12 26 4
gpt4 key购买 nike

我在 JSP 文件中有以下代码片段。在此代码片段中,我使用 IP 地址构成 URL。我想要的不是 IP 地址,而是域名。 (这里的域名,我指的是我在主机文件中为localhost定义的条目。如果没有定义,它应该返回可能是机器名。这就是我认为应该的)

  String ip = "";
InetAddress inetAddress = InetAddress.getLocalHost();
ip = inetAddress.getHostAddress();
appUrl=<%=(new java.net.URL(request.getScheme(),ip,request.getServerPort(), "")).toString() %>

我尝试了这些选项

  inetAddress.getCanonicalHostName();
inetAddress.getHostName();

但两者都返回计算机名称。我该如何获取域名?

编辑以澄清更多信息我已在主机文件中声明了条目,即 127.0.0.1 myProjectApp。所以在这种情况下我想形成像http://myProjectApp/这样的url但如果我不贴花它应该返回机器名称,如 http://machineName/ 。其背后的意图是我将此网址发送到网络上的另一台机器(例如 B)。使用此 URL 机器 B 将反向连接到 A。希望它能澄清

最佳答案

有两种获取域名/主机名的方法,但它们标识不同的东西。一个标识客户端使用的 URL,另一个标识部署描述符中定义的 Servlet 名称。

检索客户端使用的域:

int port = request.getServerPort();

// if port is default or 0, just use the default port.
String appUrl =
request.getScheme() + "://" + request.getServerName();

// if it's not the default port, append the port to your url
if(port != 80 || port != 443 || port != 0) {
appUrl += ":" + new Integer(port).toString();
}

检索 Servlet 使用的主机::

String servletContextName = request.getServletContext().getServletContextName();

参见ServletContext.getServletContextName() :

public java.lang.String getServletContextName()

Returns the name of this web application correponding to this ServletContext as specified in the deployment descriptor for this web application by the display-name element.

Returns: The name of the web application or null if no name has been declared in the deployment descriptor.

Since: Servlet 2.3

关于java - java中如何从host文件中获取域名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9545643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com