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"
+ " |(_ o _) / _( )_ .' n" + " | (_,_).' __ ___(_ o _)' 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----------------------------------------------------------nt" +
"Application is running! Access URLs:nt" +
"Local訪問網址: tthttp://localhost:" + port + path + "nt" +
"External訪問網址: thttp://" + ip + ":" + port + path + "nt" +
"----------------------------------------------------------");
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
log.info("當前項目進程號:" + jvmName.split("@")[0]);
}
2、此外,還可以設置打開系統默認瀏覽器,並加載指定的頁面。如下添加監聽類。

示例代碼:
package com.yc.star.web.utils;
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("瀏覽器打開頁面異常");
}
}
}
}
在”IT人才圈”微信公眾號,發送”01″可獲取更多相關源碼教程或交流。
3、在application.yml文件中配置相關的參數:

spring:
auto:
openurl: true # 是否自動打開瀏覽器,false為否
web:
loginurl: http://localhost:8090 # 指定加載的頁面地址
至此,可愉快地啟動項目,等待瀏覽器自動加載我們指定的頁面。
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/217025.html
微信掃一掃
支付寶掃一掃