8

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

What if I need the same functionality inside the initialization of a servlet? How do I do this?

2
  • 2
    Are there any problems/issues if I invoke java.net.InetAddress.getLocalHost().getCanonicalHostName() to get the server name? Commented Nov 4, 2010 at 23:44
  • yes, when you have alias names for your host. For example your application may be visible under http://www.google.com/ while using getCanonicalHostName() may give you http://nuq05s02-in-f18.1e100.net/ Commented Feb 27, 2015 at 16:18

4 Answers 4

4

This information is request based and not strictly application based. It can namely change per request. All you have at hands during servlet initialization is the ServletContext instance which in turn offers methods like getInitParameter(). You could make use of it to access application wide settings.

So your best bet is to manually set the server name as a context parameter in web.xml

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

so that you can obtain it as follows in servlet's init() method:

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

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

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

so that you can obtain it as follows:

String serverName = getServletContext().getServletContextName();
Sign up to request clarification or add additional context in comments.

Comments

3

If for some reason you don't want to use BalusC's answer, and you don't need the name immediately, you can do it lazily. The other day I implemented a similar scenario that way:

private volatile boolean initialized;

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

(The double-checked locking for lazy-initialization may be implemented in multiple ways. See wikipedia)

Comments

1

InetAddress.getLocalHost().getHostName()

Comments

0

I think that's not possible. A host can have multiple names. Which one should be returned? And the host might not even know about all names that are configured in DNS.

2 Comments

I think the asker wants to get the same value as from HttpServletRequest.getServerName() but from a generic HttpServlet. There is standard behaviour for which name to return.
The HttpServletRequest does contain a server name because the web browser sends one. On initialization of the servlet there is no request around to read the server name from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.