开发者

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

开发者 https://www.devze.com 2022-12-26 03:15 出处:网络
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 b

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.


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


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


I have found in my old project the string:

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

maybe it is the solution?

0

精彩评论

暂无评论...
验证码 换一张
取 消