How can I get a the host name (with port) that a servlet is at

扶醉桌前 提交于 2019-11-28 06:43:48
Everyone
ServletRequest.getServerName(...)
ServletRequest.getServerPort(...)

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());
}

@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
user310791

I have found in my old project the string:

request.getHeader("host").contains("xxx")

maybe it is the solution?

Fang Zhen

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!