在ContextLoaderListener中获取服务器名称

3

我的监听器正在填充缓存(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
    }
}

1
我很好奇你为什么要扩展Spring的ContextLoaderListener,然后覆盖它的方法。这样做留下来的只是一个普通的ServletContextListener,没有任何Spring行为。 - skaffman
4个回答

5

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

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

String hostname = InetAddress.getLocalHost().getHostName();

1

HttpServletRequest.getServerName():

返回发送请求的服务器的主机名。它不是服务器本身的属性,而是请求的属性。在ContextLoaderListener的上下文之外没有意义。您实际上要查找什么信息?

0

简单来说:

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
....

ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest req = sra.getRequest();
String serverName = req.getServerName();

0
如果你只是想确定自己是否在本地主机上:
boolean isLocalHost = "localhost/127.0.0.1".equals(InetAddress.getLoopbackAddress().toString());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接