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\")
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
The ServletRequest object that has been passed to your doGet, or doPost method has getServerName
and getServerPort
methods that provide this information.
eg
public void doGet(ServletRequest request, ServletResponse response) {
System.out.println("Host = " + request.getServerName());
System.out.println("Port = " + request.getServerPort());
}
I have found in my old project the string:
request.getHeader("host").contains("xxx")
maybe it is the solution?
ServletRequest.getServerName(...)
ServletRequest.getServerPort(...)
@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.
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
String host = url.substring(0, url.indexOf(uri)); //result