如何在Spring Boot应用程序中使用域,端口和路径获取特定的应用程序路由?

问题描述

我在StackOverflow中发现了类似的问题,但是没有公认的答案。

get application domain + port and path programmatically in spring?

我要发送电子邮件验证链接。 例如:https:// host:port / path?encrypted_email = encrypted-data-of-user-email

我想将此URL从注册控制器发送到用户的电子邮件中。但是,我不会写Http / https,主机,端口和硬编码电子邮件的验证路径。我想借助Spring Boot的帮助来解决这个问题。我该怎么办,如何克服这种情况?

谢谢

解决方法

在所有地方搜索后,包括StackOverflow。我发现了:

获得主持人:

String host = InetAddress.getLocalHost().getHostName();

获取端口:

// In your application.properties
server.port=8080
String port = environment.getProperty("server.port");

我还在上面写了一个示例类。

import org.springframework.core.env.Environment;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ApiUrl {

    private final Environment environment;
    public static final String apiUrlPrefix = "/api";
    public static final String apiVersion = "/v1";

    public ApiUrl(Environment environment) {
        this.environment = environment;
    }

    public String getApiBaseUrl() throws UnknownHostException {
        String host = InetAddress.getLocalHost().getHostName();
        String port = environment.getProperty("server.port");

        return "https://" + host +":"+ port + apiUrlPrefix + apiVersion;
    }
}

我希望这会对人们有所帮助。

更多研究参考:

https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html