如何获取 servlet 所在的主机名(带端口)
我认为 ServletContext 可能提供一种方法。 ServletContext 的 getAttribute() 方法是否提供任何帮助,即是否存在有帮助的属性名称(可能是“主机”、“端口”)。
原因是我希望我的应用程序能够在部署的任何地方运行,并且在某一时刻我必须允许用户单击指向文件服务器上某个位置的链接。因此,我需要通过主机和端口进行引用,并且不能使用内部引用。
I thought ServletContext might provide a method. Does the getAttribute() method of ServletContext provide any help i.e. is there an attribute name (maybe "host", "port") that will be of help.
The reason for this is I want my application to run wherever it is deployed, and at one point I have to allow a user to click a link that points to a location on the file server. Hence I need to reference by the host and port and cannot use an internal reference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我在旧项目中发现了字符串:
request.getHeader("host").contains("xxx")
也许这是解决方案?
I have found in my old project the string:
request.getHeader("host").contains("xxx")
maybe it is the solution?
已传递给 doGet 或 doPost 方法的 ServletRequest 对象具有提供此信息的
getServerName
和getServerPort
方法。例如
The ServletRequest object that has been passed to your doGet, or doPost method has
getServerName
andgetServerPort
methods that provide this information.eg
@每个人都有一个很好的答案。但是采用方案、服务器名称和端口然后合并它们。有一种更简单的方法:
您可以使用 HttpServletRequest.getRequestURL 和 HttpServletRequest.getRequestURI。
@Everyone has a good answer. But taking scheme, server name and port then mergin them. There is a simpler way:
You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.
正如上面提到的,可以通过请求检索主机和端口。另一方面,ServletContext 不可能提供信息,因为 java 应用程序不知道您的主机环境。即,具有上下文路径“foo”(可以通过 ServletContext#getContextPath() 检索)的应用程序可以接收来自 http 端口 8080 和 https 端口 8043 的请求。 archive.org/web/20120401225136/http://www.java.net:80/node/701934" rel="nofollow noreferrer">https://web.archive.org/web/20120401225136/http://www .java.net:80/node/701934
As others mentioned above, host and port can be retrieved through request. On the other hand, it is impossible for the ServletContext provide the info since java applications are unaware of your host environment. i.e., an application with context path "foo"(which could be retrieved by ServletContext#getContextPath()) could receive requests both from a http port 8080 and a https port 8043. Reference: https://web.archive.org/web/20120401225136/http://www.java.net:80/node/701934