Getting server name during servlet initialization

I know that the request object has a function to get the server name. (i.e.HttpServletRequest.getServerName ())

What if I need the same functionality inside servlet initialization? How to do it?

+6
servlets
source share
4 answers

This information is based on queries, not strictly application-based. This can be changed upon request. All you have during servlet initialization is the ServletContext , which in turn offers methods like getInitParameter() . You can use it to access wide application settings.

So, it’s best to manually set the server name as the context parameter in web.xml

 <context-param> <param-name>serverName</param-name> <param-value>foo</param-value> <context-param> 

so that you can get it like this in the init() servlet method:

 String serverName = getServletContext().getInitParameter("serverName"); 

Another (not recommended) option is to set it as a display name in web.xml

 <display-name>foo</display-name> 

so that you can get it like this:

 String serverName = getServletContext().getServletContextName(); 
+4
source share

If for some reason you do not want to use the BalusC answer, and you do not need a name right away, you can do it lazily. The other day I implemented a similar scenario this way:

 private volatile boolean initialized; public void doGet(..) { if (!initialized) { synchronized(this) { if (!initialized) { initialize(request.getServerName()) } } } } 

(Double locking check for lazy initialization can be implemented in several ways. See wikipedia )

+3
source share

I think that this is impossible. A host can have multiple names. Which one needs to be returned? And the host may not even know about all the names configured in DNS.

0
source share

InetAddress.getLocalHost (). GetHostName ()

0
source share

All Articles