如何获取servlet所在的主机名(带端口)

Ank*_*kur 43 java servlets hostname

我认为ServletContext可能会提供一种方法.ServletContext的getAttribute()方法是否提供任何帮助,即是否有帮助的属性名称(可能是"host","port").

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

Eve*_*one 60

ServletRequest.getServerName(...)
ServletRequest.getServerPort(...)
Run Code Online (Sandbox Code Playgroud)

  • 这些方法只是使用请求中“Host”标头的值,但使用起来并不总是安全的,因为任何人都可以更改它,包括客户端和服务器之间的任何代理。例如,如果您的 Tomcat 实例位于 Apache 服务器后面,这些方法可能会返回本地主机地址(请参阅[此答案](/sf/answers/1503752771/) 上的评论) (2认同)

Tom*_*rys 15

已传递到您的doGet或doPost方法的ServletRequest对象具有getServerNamegetServerPort提供此信息的方法.

例如

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


Ami*_*t G 5

@Everyone有一个很好的答案.但是采取方案,服务器名称和端口然后开始使用它们.有一种更简单的方法:

您可以使用HttpServletRequest.getRequestURLHttpServletRequest.getRequestURI.

StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
String host = url.substring(0, url.indexOf(uri)); //result
Run Code Online (Sandbox Code Playgroud)