开发者

Getting server name during servlet initialization

开发者 https://www.devze.com 2023-01-23 08:28 出处:网络
I know the request object has a function to get the server name. (i.e. HttpServletRequest.getServerName() )

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?


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();


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)


InetAddress.getLocalHost().getHostName()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消