获取服务器地址和应用程序名称

环境:NetBeans 6.9.1,GlassFish 3.1

我有一个Java Web应用程序。 如何动态获取服务器地址和应用程序名称? ‘2in1’解决方案对我来说是最好的: http://localhost:8080/AppName/

有没有实用的方法来获取这些信息?

假设AppName的值将被修复,所以我只需要主机地址。 是否可以通过JMX检索它? 还有其他方法吗?

HttpServletRequest对象将为您提供所需内容:

  • HttpServletRequest#getLocalAddr() :服务器的IP地址为字符串
  • HttpServletRequest#getLocalName() :接收请求的服务器的名称
  • HttpServletRequest#getServerName() :请求发送到的服务器的名称
  • HtppServletRequest#getLocalPort() :服务器收到请求的端口
  • HttpServletRequest#getServerPort() :请求发送到的端口
  • HttpServletRequest#getContextPath() :标识应用程序的路径部分

在servlet中你可以像这样得到它

 public static String getUrl(HttpServletRequest request) { return request.getRequestURL().toString(); }