我该如何获取一个servlet所在的主机名(包含端口)?

45

我认为 ServletContext 可能提供一个方法。ServletContext 的 getAttribute() 方法是否提供任何帮助,例如是否有一个属性名称(可能是"host"、"port"),对解决问题有帮助。

原因是我希望我的应用程序在部署在任何地方都能运行,并且在某一点上,我必须允许用户单击指向文件服务器位置的链接。因此,我需要通过主机和端口引用,不能使用内部引用。

5个回答

61
ServletRequest.getServerName(...)
ServletRequest.getServerPort(...)

这个不再起作用了。我现在还在找出如何做它。 - Benny Bottema
2
这些方法简单地使用请求中的“Host”头的值,但并不总是安全的,因为它可以被任何人(包括客户端和服务器之间的任何代理)更改。 因此,例如,如果您的Tomcat实例在Apache服务器后面,这些方法可能会返回本地主机地址(请参见this answer上的评论)。 - typeracer

16

您的doGetdoPost方法传递的ServletRequest对象具有getServerNamegetServerPort方法,可提供此信息。

例如:

public void doGet(ServletRequest request, ServletResponse response) {
    System.out.println("Host = " + request.getServerName());
    System.out.println("Port = " + request.getServerPort());
}

1
获取URL的方法:request.getServerName() + ":" + request.getServerPort(); - Simon Bengtsson

8

@每个人都有一个好答案。但是,将方案、服务器名称和端口合并起来。有一种更简单的方法:

你可以使用HttpServletRequest.getRequestURLHttpServletRequest.getRequestURI

StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
String host = url.substring(0, url.indexOf(uri)); //result

4
正如其他人所提到的,主机和端口可以通过请求来获取。另一方面,由于Java应用程序不知道您的主机环境,因此ServletContext无法提供该信息。例如,具有上下文路径“foo”的应用程序(可通过ServletContext#getContextPath()检索)可以从http端口8080和https端口8043接收请求。参考:https://web.archive.org/web/20120401225136/http://www.java.net:80/node/701934

3
我在我的旧项目中找到了以下字符串: request.getHeader("host").contains("xxx") 也许这就是解决方案?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接