更简单的一个方法
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
Springboot项目启动后自动打开浏览器访问(超实用)_浏览器访问springboot项目-CSDN博客
Springboot项目启动后自动打开浏览器访问
1、在Springboot项目中每次启动完项目,手动在浏览器输入访问地址太麻烦了。在启动类中加入下方代码,就可高效地在控制台中单击URL访问项目了~
示例代码:
@SpringBootApplication
@Slf4j
public class WebApplication {
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext application = SpringApplication.run(WebApplication.class, args);
System.out.println(
" ____ __ __ ___ ___ __ ____ ____ \n" +
" /',__\\/\\ \\/\\ \\ /'___\\ /'___\\ /'__`\\ /',__\\ /',__\\ \n" +
"/\\__, `\\ \\ \\_\\ \\/\\ \\__//\\ \\__//\\ __//\\__, `\\/\\__, `\\\n" +
"\\/\\____/\\ \\____/\\ \\____\\ \\____\\ \\____\\/\\____/\\/\\____/\n" +
" \\/___/ \\/___/ \\/____/\\/____/\\/____/\\/___/ \\/___/ \n");
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
if (StringUtils.isEmpty(path)) {
path = "";
}
log.info("\n----------------------------------------------------------\n\t" +
"Application is running! Access URLs:\n\t" +
"Local访问网址: \t\thttp://localhost:" + port + path + "\n\t" +
"External访问网址: \thttp://" + ip + ":" + port + path + "\n\t" +
"----------------------------------------------------------");
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
log.info("当前项目进程号:" + jvmName.split("@")[0]);
}
2、此外,还可以设置打开系统默认浏览器,并加载指定的页面。如下添加监听类。
示例代码:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* spring boot 容器加载后自动监听
*/
@Component
public class MyCommandRunner implements CommandLineRunner {
@Value("${spring.web.loginurl}")
private String loginUrl;
@Value("${spring.auto.openurl}")
private boolean isOpen;
@Override
public void run(String... args) {
if (isOpen) {
System.out.println("自动加载指定的页面");
try {
Runtime.getRuntime().exec("cmd /c start " + loginUrl); // 可以指定自己的路径
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("浏览器打开页面异常");
}
}
}
}
3、在application.yml文件中配置相关的参数:
spring:
auto:
openurl: true # 是否自动打开浏览器,false为否
web:
loginurl: http://localhost:8090 # 指定加载的页面地址
至此,可愉快地启动项目,等待浏览器自动加载我们指定的页面。
————————————————
版权声明:本文为CSDN博主「flash&」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/rongbo91/article/details/109668937