如果你把应用打包成WAR文件,配置一个应用服务器,比如Tomcat,然后通过你的IDE重启配置的应用服务器,IDE可以自动打开一个浏览器标签。
如果您想将应用程序打包为JAR 文件,您的IDE 将无法打开Web 浏览器,因此您必须打开Web 浏览器并键入所需的链接(localhost:8080)。但在开发阶段,采取这些无聊的步骤可能会非常乏味。
在 spring-boot 应用程序准备好后,可以使用 Java 编程语言打开浏览器。可以使用Selenium之类的第三方库或者使用如下代码sn-p。
打开浏览器的代码sn-p
@EventListener({ApplicationReadyEvent.class})
private void applicationReadyEvent()
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e)
{
e.printStackTrace();
}
} else
{
Runtime runtime = Runtime.getRuntime();
String[] command;
String operatingSystemName = System.getProperty("os.name").toLowerCase();
if (operatingSystemName.indexOf("nix") >= 0 || operatingSystemName.indexOf("nux") >= 0)
{
String[] browsers = {"opera", "google-chrome", "epiphany", "firefox", "mozilla", "konqueror", "netscape", "links", "lynx"};
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
{
if (i == 0) stringBuffer.append(String.format("%s \"%s\"", browsers[i], url));
else stringBuffer.append(String.format(" || %s \"%s\"", browsers[i], url));
}
command = new String[]{"sh", "-c", stringBuffer.toString()};
} else if (operatingSystemName.indexOf("win") >= 0)
{
command = new String[]{"rundll32 url.dll,FileProtocolHandler " + url};
} else if (operatingSystemName.indexOf("mac") >= 0)
{
command = new String[]{"open " + url};
} else
{
System.out.println("an unknown operating system!!");
return;
}
try
{
if (command.length > 1) runtime.exec(command); // linux
else runtime.exec(command[0]); // windows or mac
} catch (IOException e)
{
e.printStackTrace();
}
}
}
使用 Selenium 打开浏览器
要使用 selenium 库,请将以下依赖项添加到您的 pom.xml 文件中。
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
然后在你的主类中,添加以下代码sn-p。
@EventListener({ApplicationReadyEvent.class})
private void applicationReadyEvent()
{
String url = "http://localhost:8080";
// pointing to the download driver
System.setProperty("webdriver.chrome.driver", "Downloaded-PATH/chromedriver");
ChromeDriver chromeDriver = new ChromeDriver();
chromeDriver.get(url);
}
注意:FirefoxDriver、OperaDriver、EdgeDriver等大多数流行浏览器都可以使用,但需要事先下载浏览器的驱动程序。