How to determine the url of a Java web application from the inside?

My Java web application has a launch servlet. Its method init()is called when the web application server (Tomcat) starts. As part of this method, I need the URL of my web application. Since no HttpServletRequest, how to get this information?

+3
source share
4 answers

Here's how it works for me, and probably for most configurations:

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;
}
+1
source

. "URL- - Java", "". URL-, . (, Apache, Tomcat - Tomcat ) HttpServletRequest URL-, (URL-, ), URL- .

+5

. , , . boolean . , , . .

+1

The servlet API does not have this information, plus any given resource can be bound to multiple URLs.

What you can do is check the servlet context when you receive the actual request and see which URL was used.

+1
source

Source: https://habr.com/ru/post/1752266/


All Articles