在ContextLoaderListener中获取服务器名称

Tri*_*ick 3 java spring request listener

我的监听器正在填充Cache(Terracota),如果在应用程序启动时出现问题,则抛出ExceptionInInitializerError.我想获取服务器名称(如在HttpServletRequest - getServerName()上)以了解这发生的位置.

我怎么才能得到这个信息?

import javax.servlet.ServletContextEvent;

import net.f.core.service.util.CacheUtil;

import org.apache.log4j.Logger;
import org.springframework.web.context.ContextLoaderListener;

/**
 * Application Lifecycle Listener implementation class OnContextLoadListener
 * 
 */
public class OnContextLoadListener extends ContextLoaderListener {

private static final Logger log = Logger
        .getLogger(OnContextLoadListener.class);

@Override
public void contextDestroyed(
        @SuppressWarnings("unused") ServletContextEvent sce) {
    // nothing here
}

@Override
public void contextInitialized(
        @SuppressWarnings("unused") ServletContextEvent sce) {

    try {
        CacheUtil.getInstance();
    } catch (ExceptionInInitializerError e) {
        log.error("Problem with application start!", e);
        // notify me
    }
}
Run Code Online (Sandbox Code Playgroud)

rsp*_*rsp 5

服务器主机名是请求的一部分,因为它取决于客户端用于访问主机的URL.

如果您对本地主机名感兴趣,可以尝试:

String hostname = InetAddress.getLocalHost().getHostName();
Run Code Online (Sandbox Code Playgroud)