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

后端 未结 5 1476
滥情空心
滥情空心 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: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
    

提交回复
热议问题