在spring-boot web应用准备就绪后自动启动浏览器

20

如何在启动Spring Boot应用程序后自动启动浏览器?是否有监听器方法回调来检查Web应用程序是否已部署并准备好为请求提供服务,以便加载浏览器时,用户可以看到索引页面并开始与Web应用程序交互?

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
    // launch browser on localhost 
}
6个回答

21

以下代码对我有效:

@EventListener({ApplicationReadyEvent.class})
void applicationReadyEvent() {
    System.out.println("Application started ... launching browser now");
    browse("www.google.com");
}

public static void browse(String url) {
    if(Desktop.isDesktopSupported()){
        Desktop desktop = Desktop.getDesktop();
        try {
            desktop.browse(new URI(url));
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }else{
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

9
@SpringBootApplication
@ComponentScan(basePackageClasses = com.io.controller.HelloController.class)
public class HectorApplication {

    public static void main(String[] args) throws IOException {
       SpringApplication.run(HectorApplication.class, args);
       openHomePage();
    }

    private static void openHomePage() throws IOException {
       Runtime rt = Runtime.getRuntime();
       rt.exec("rundll32 url.dll,FileProtocolHandler " + "http://localhost:8080");
    }
}

只是稍微改进一下..我认为不要像@theSushil建议的那样在main中调用openHomePage(),而是添加注释将其附加到ApplicationReadyEvent似乎更好。然而这个方法也可以。你有我的赞成。 - Danish Javed

6
你可以通过一些Java代码来完成。我不确定Spring Boot是否有现成的解决方案。
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Browser {
    public static void main(String[] args) {
        String url = "http://www.google.com";

        if(Desktop.isDesktopSupported()){
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(new URI(url));
            } catch (IOException | URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("xdg-open " + url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

也许我应该详细说明一下,我想要像beanpostconstruct一样的回调函数,以便让我知道Web上下文何时准备好提供服务,然后我可以像上面的代码一样打开浏览器或使用浏览器启动库。 - Tito
在运行run方法之后,应用程序已准备就绪... 所以你可以在此之后启动你的浏览器。 - M. Deinum
你的意思是说 run 方法是一个阻塞调用吗? - Tito
1
run方法将为您提供一个完全配置好的、因此准备就绪的“ApplicationContext”。 - M. Deinum

2

如果您将应用程序打包为WAR文件,请配置应用程序服务器(如Tomcat),并通过IDE重新启动已配置的应用程序服务器,IDE可以自动打开浏览器选项卡。

如果您想将应用程序打包为JAR文件,则IDE将无法打开Web浏览器,因此您必须打开Web浏览器并键入所需的链接(localhost:8080)。但在开发阶段,执行这些繁琐的步骤可能非常乏味。

在Spring Boot应用程序准备就绪后,可以使用Java编程语言打开浏览器。您可以使用第三方库,例如Selenium,或使用以下代码片段。

打开浏览器的代码片段

@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>

然后在你的主类中,添加以下代码片段。

@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);
}

注意:可以使用大多数流行的浏览器,如FirefoxDriverOperaDriverEdgeDriver,但需要事先下载浏览器驱动程序。


1

最近我一直在尝试自己解决这个问题,虽然这个问题已经问了很久,但我的解决方案非常基本和简单,如下所示。这是任何想要解决这个问题的人的起点,在您的应用程序中根据需要进行重构!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        openHomePage();
    }

    private static void openHomePage() {
        try {
            URI homepage = new URI("http://localhost:8080/");
            Desktop.getDesktop().browse(homepage);
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        }
    }
}

0
Runtime rt = Runtime.getRuntime();
        try {
            rt.exec("cmd /c start chrome.exe https://localhost:8080");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

上面的代码对我有效。将chrome.exe更改为您选择的浏览器,将Url更改为您选择的网址。 注意:您必须包括方案 - http或https,并且您选择的浏览器必须已安装,否则您的应用程序将在不自动打开浏览器的情况下运行。 仅适用于Windows

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接