8

Environment: NetBeans 6.9.1, GlassFish 3.1

I have a Java Web Application. How to get the server address and the application name dynamically? The '2in1' solution would be the best for me: http://localhost:8080/AppName/.

Is there a practical way to get that information?

Let's say the value of AppName will be fixed, so I only need the host address. Is it possible to retrieve it via JMX? Any other ways?

Zoe stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
Daniel Szalay
  • 3,942
  • 12
  • 56
  • 100

2 Answers2

32

The HttpServletRequest object will give you what you need:

  • HttpServletRequest#getLocalAddr(): The server's IP address as a string
  • HttpServletRequest#getLocalName(): The name of the server receiving the request
  • HttpServletRequest#getServerName(): The name of the server that the request was sent to
  • HtppServletRequest#getLocalPort(): The port the server received the request on
  • HttpServletRequest#getServerPort(): The port the request was sent to
  • HttpServletRequest#getContextPath(): The part of the path that identifies the application
cassiomolin
  • 113,708
  • 29
  • 249
  • 319
Simon G.
  • 6,427
  • 23
  • 29
  • 11
    @Ging3r No. It is not. Perhaps you should heed your own advice about paying attention and read the appropriate documentation? – Simon G. Nov 14 '12 at 23:05
  • What does that pound sign in method name mean? I've never seen it before. – Scott Chu May 24 '18 at 06:24
  • @ScottChu - I honestly cannot remember where I copied the above from 5 years ago. I agree that the "HttpServletRequest#" prefix is unusual and unnecessary. – Simon G. May 24 '18 at 14:42
  • ClassName#MethodName is a notation used in JavaDoc, for example within @see tag. – predrags Jun 19 '19 at 09:44
3

Inside a servlet you can get it like this

public static String getUrl(HttpServletRequest request) {
    return request.getRequestURL().toString();
}
Renato Pradebon
  • 2,043
  • 2
  • 7
  • 6
Jim Blackler
  • 22,543
  • 11
  • 83
  • 100