Java 正在ContextLoaderListener中获取服务器名称
我的侦听器正在填充缓存(Terracota),如果应用程序启动时出现问题,将抛出ExceptionInInitializerError。我想获取服务器名(如HttpServletRequest-getServerName())以了解这是在哪里发生的 我怎样才能得到这个信息Java 正在ContextLoaderListener中获取服务器名称,java,spring,request,listener,Java,Spring,Request,Listener,我的侦听器正在填充缓存(Terracota),如果应用程序启动时出现问题,将抛出ExceptionInInitializerError。我想获取服务器名(如HttpServletRequest-getServerName())以了解这是在哪里发生的 我怎样才能得到这个信息 import javax.servlet.ServletContextEvent; import net.f.core.service.util.CacheUtil; import org.apache.log4j.Log
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
}
}
HttpServletRequest.getServerName()
:
将服务器的主机名返回到
请求被发送到的
它不是服务器本身的属性,而是请求的属性。它在ContextLoaderListener
的上下文之外没有任何意义
您实际上在寻找什么信息?服务器主机名是请求的一部分,因为它取决于客户端用来访问主机的URL 如果您对本地主机名感兴趣,可以尝试:
String hostname = InetAddress.getLocalHost().getHostName();
简单地说:
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();
如果您只是想确定自己是否在
localhost
:
布尔值isLocalHost=“localhost/127.0.0.1”。等于(InetAddress.getLoopbackAddress().toString());
我很好奇为什么要扩展Spring的ContextLoaderListener
,然后超越它的方法。剩下的只是一个普通的ServletContextListener
,没有Spring行为。