[英]How can I get my local host and port in a Java servlet method init()?
[英]How can I get a the host name (with port) that a servlet is at
我認為ServletContext可能會提供一種方法。 ServletContext的getAttribute()方法是否提供任何幫助,即是否有幫助的屬性名稱(可能是“host”,“port”)。
原因是我希望我的應用程序在部署的任何地方運行,並且有一點我必須允許用戶單擊指向文件服務器上某個位置的鏈接。 因此我需要通過主機和端口引用,不能使用內部引用。
ServletRequest.getServerName(...)
ServletRequest.getServerPort(...)
已傳遞給doGet或doPost方法的ServletRequest對象具有提供此信息的getServerName
和getServerPort
方法。
例如
public void doGet(ServletRequest request, ServletResponse response) {
System.out.println("Host = " + request.getServerName());
System.out.println("Port = " + request.getServerPort());
}
@Everyone有一個很好的答案。 但是采取方案,服務器名稱和端口然后開始使用它們。 有一種更簡單的方法:
您可以使用HttpServletRequest.getRequestURL和HttpServletRequest.getRequestURI 。
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
String host = url.substring(0, url.indexOf(uri)); //result
如上所述,可以通過請求檢索主機和端口。 另一方面,ServletContext不可能提供信息,因為Java應用程序不知道您的主機環境。 即,具有上下文路徑“foo”的應用程序(可以通過ServletContext#getContextPath()檢索)可以從http端口8080和https端口8043接收請求。參考: https ://web.archive.org/web /20120401225136/http://www.java.net:80/node/701934
我在我的舊項目中找到了字符串:
request.getHeader("host").contains("xxx")
也許這是解決方案?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.