我的Java Web应用程序包含一个启动servlet,当Web应用程序服务器(Tomcat)启动时,它的init()
方法被调用。在这个方法中,我需要获取我的Web应用程序的URL。由于没有HttpServletRequest
,如何获取这些信息?
我的Java Web应用程序包含一个启动servlet,当Web应用程序服务器(Tomcat)启动时,它的init()
方法被调用。在这个方法中,我需要获取我的Web应用程序的URL。由于没有HttpServletRequest
,如何获取这些信息?
以下是它对我以及大多数配置的工作方式:
public static String getWebappUrl(ServletConfig servletConfig, boolean ssl) {
String protocol = ssl ? "https" : "http";
String host = getHostName();
String context = servletConfig.getServletContext().getServletContextName();
return protocol + "://" + host + "/" + context;
}
public static String getHostName() {
String[] hostnames = getHostNames();
if (hostnames.length == 0) return "localhost";
if (hostnames.length == 1) return hostnames[0];
for (int i = 0; i < hostnames.length; i++) {
if (!"localhost".equals(hostnames[i])) return hostnames[i];
}
return hostnames[0];
}
public static String[] getHostNames() {
String localhostName;
try {
localhostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException ex) {
return new String[] {"localhost"};
}
InetAddress ia[];
try {
ia = InetAddress.getAllByName(localhostName);
} catch (UnknownHostException ex) {
return new String[] {localhostName};
}
String[] sa = new String[ia.length];
for (int i = 0; i < ia.length; i++) {
sa[i] = ia[i].getHostName();
}
return sa;
}
在Servlet API中没有提供这些信息,而且任何给定的资源可能绑定到多个URL。
你可以做的是,在收到实际请求时检查servlet上下文,并查看使用了哪个URL。