方法一:
在项目中创建一个config类,并实现ApplicationListener接口
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
private int serverPort;
public String getUrl() {
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
return address.getHostAddress() +":"+this.serverPort;
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
this.serverPort = event.getWebServer().getPort();
}
}
输出:127.0.0.1:8080
方法二:
通过controller层方法参数中的 HttpServletRequest对象
方法三:
如果一些方法中没有 HttpServletRequest对象,可以通过 RequestContextHolder类的静态方法获取当前的request。