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 c开发者_Python百科lass 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
}
}
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();
HttpServletRequest.getServerName()
:
Returns the host name of the server to which the request was sent.
Its not a property of the server itself, it's a property of the request. It makes no sense outside of the context of the ContextLoaderListener
.
What information are you actually looking for?
Simply:
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();
If you're just trying to determine if you're on localhost
:
boolean isLocalHost = "localhost/127.0.0.1".equals(InetAddress.getLoopbackAddress().toString());
精彩评论