Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch browser automatically after spring-boot webapp is ready

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 
}
like image 906
Tito Avatar asked Dec 09 '14 11:12

Tito


People also ask

What is the default web browser used in spring boot application?

Use AWT Desktop class to launch default browser at local host:8080 where Spring Boot application is served by default.

How do I test my browser spring boot?

The first is you need to annotate your tests with the @RunWith annotation and specify that you want to run it with the SpringJUnit4ClassRunner. class . The second is you need to add the @SpringApplicationConfiguration annotation and provide your main Spring Boot class for your application.

What happens with @SpringBootApplication?

Spring Boot Auto Configuration automatically configures your Spring application based on the JAR dependencies you added in the project. For example, if MySQL database is on your class path, but you have not configured any database connection, then Spring Boot auto configures an in-memory database.


2 Answers

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();
        }
    }
}
like image 137
theSushil Avatar answered Sep 28 '22 05:09

theSushil


@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");
    }
}
like image 37
Vivek Mishra Avatar answered Sep 28 '22 05:09

Vivek Mishra