20

How do I launch a browser automatically after starting the spring boot application.Is there any listener method callback to check if the webapp has been deployed and is ready to serve the requests,so that when the browser is loaded , the user sees the index page and can start interacting with the webapp?

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
    // launch browser on localhost 
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
Tito
  • 8,894
  • 12
  • 52
  • 86

6 Answers6

21

Below code worked for me:

@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();
        }
    }
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
theSushil
  • 460
  • 7
  • 13
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");
    }
}
cela
  • 2,352
  • 3
  • 21
  • 43
Vivek Mishra
  • 367
  • 3
  • 5
  • Just to improvise a little.. I think instead of calling the openHomePage() in main, like @theSushil suggested, adding annotation to attach it to ApplicationReadyEvent seems better. However this worked fine. You have my upvote – Danish Javed Jun 17 '22 at 18:17
6

You could do it by some java code. I am not sure if spring boot has something out of the box.

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();
            }
        }
    }
}
Andy Dufresne
  • 6,022
  • 7
  • 63
  • 113
  • Maybe I should elaborate , I would like to get a callback like beanpostconstruct to let me know if the web context is ready to serve,then I can open browser like the above code or use a browser launcher library. – Tito Dec 09 '14 at 12:07
  • After the run method the application is ready... So you can just launch your browser after that. – M. Deinum Dec 09 '14 at 12:19
  • You mean to say the run method is a blocking call ? – Tito Dec 09 '14 at 12:27
  • 1
    yes. The run method will give you a fully configured, and thus ready, `ApplicationContext`. – M. Deinum Dec 09 '14 at 12:46
2

If you package the application as a WAR file, configure an application server, like Tomcat, and restart the configured application server through your IDE, IDEs can automatically open a browser-tab.

If you want to package your application as a JAR file, your IDE will not be able to open a web browser, so you have to open a web browser and type the desired link(localhost:8080). But in the developing phase, taking these boring steps might be very tedious.

It is possible to open a browser with Java programming language after the spring-boot application gets ready. You can use the third-party library like Selenium or use the following code snippet.

The code snippet to open a browser

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

Using Selenium to open a browser

To use the selenium library add the following dependency to your pom.xml file.

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>

Then in your main class, add the following code snippet.

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

Notice: It is possible to use most of the popular browsers like FirefoxDriver, OperaDriver, EdgeDriver, but it is necessary to download browsers' drivers beforehand.

Elyas Hadizadeh
  • 3,289
  • 8
  • 40
  • 54
1

I've recently been attempting to get this working myself, I know it's been a while since this question was asked but my working (and very basic/simple) solution is shown below. This is a starting point for anyone wanting to get this working, refactor as required in your app!

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();
        }
    }
}
mvee
  • 263
  • 2
  • 15
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();
        }

The code above worked for me. Change chrome.exe to the browser of your choice and Url to to your choice. Note: You must include the scheme - http or https, and the browser you choose must me installed, else your app will run without opening the browser automatically. Works only for windows though.