有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在spring boot应用程序中获得具有域、端口和路径的特定应用程序路由?

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

get application domain + port and path programmatically in spring?

我想发送电子邮件验证链接。 例如:https://host:port/path?encrypted_email=encrypted-用户电子邮件数据

我想从注册控制器将此URL发送到用户的电子邮件。但我不会编写验证电子邮件硬编码的Http/https、主机、端口和路径。我想在spring boot的帮助下得到它。我能做什么,如何克服这种情况

谢谢


共 (1) 个答案

  1. # 1 楼答案

    在到处搜索后,包括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