Benedictus Benedictus - 1 month ago 28
Java Question

Spring boot get application base url outside of servlet context

The setup is following - I have a timed task that would send verification emails so users:

@Scheduled(cron = " 0 0-59/1 * * * * ")
public void sendVerificationEmails() {
//...
}


And in those emails I need to include a link leading back to the same webapp. However I can not find any references of how to get app's base url without servlet context.

BONUS

It would also help if I could set up thymeleaf template resolver here to work with those links, but for that I need a
WebContext
which requires an instance of
HttpServletRequest
.

Answer

Suppose your app is using embedded tomcat server, then url to your app may be found as follows:

@Inject
private EmbeddedWebApplicationContext appContext;

public String getBaseUrl() throws UnknownHostException {
    Connector connector = ((TomcatEmbeddedServletContainer) appContext.getEmbeddedServletContainer()).getTomcat().getConnector();
    String scheme = connector.getScheme();
    String ip = InetAddress.getLocalHost().getHostAddress();
    int port = connector.getPort();
    String contextPath = appContext.getServletContext().getContextPath()
    return scheme + "://" + ip + ":" + port + contextPath;
}

Here is an example for embedded jetty server:

public String getBaseUrl() throws UnknownHostException {
    ServerConnector connector = (ServerConnector) ((JettyEmbeddedServletContainer) appContext.getEmbeddedServletContainer()).getServer().getConnectors()[0];
    String scheme = connector.getDefaultProtocol().toLowerCase().contains("ssl") ? "https" : "http";
    String ip = InetAddress.getLocalHost().getHostAddress();
    int port = connector.getLocalPort();

    String contextPath = appContext.getServletContext().getContextPath();
    return scheme + "://" + ip + ":" + port + contextPath;
}