Trick Trick -4 years ago 108
Java Question

Getting server name in ContextLoaderListener

My listener is filling Cache (Terracota) and if something goes wrong at application start, ExceptionInInitializerError is thrown. I would like to get server name (like on HttpServletRequest - getServerName()) to know where this happened.

How can I come to this information??

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
}
}

Answer Source

The server hostname is part of the request, as it depends on what URL the client used to reach your host.

If you are interested in the local hostname, you can try:

String hostname = InetAddress.getLocalHost().getHostName();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download