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

后端 未结 5 1468
滥情空心
滥情空心 2020-12-08 19:06

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\")

相关标签:
5条回答
  • 2020-12-08 19:08

    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

    0 讨论(0)
  • 2020-12-08 19:12

    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());
    }
    
    0 讨论(0)
  • 2020-12-08 19:14

    I have found in my old project the string:

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

    maybe it is the solution?

    0 讨论(0)
  • 2020-12-08 19:23
    ServletRequest.getServerName(...)
    ServletRequest.getServerPort(...)
    
    0 讨论(0)
  • 2020-12-08 19:27

    @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
    
    0 讨论(0)
提交回复
热议问题