您好,登錄后才能下訂單哦!
用Spring boot搭建項目時,希望在項目啟動完后能自動談出首頁。
就用了java.awt.Desktop類
if (Desktop.isDesktopSupported()) { try { // 彈出瀏覽器 - 顯示HTTP接口(https) Desktop.getDesktop().browse(new URI("https://blog.csdn.net/weixin_42156742/article/details/81383628")); } catch (Exception e) { LOGGER.info(e.getMessage()); } }
結果在測試類里可以正常訪問,在啟動項目后卻無法彈出網頁。
public static synchronized Desktop getDesktop(){ if (GraphicsEnvironment.isHeadless()) throw new HeadlessException(); if (!Desktop.isDesktopSupported()) { throw new UnsupportedOperationException("Desktop API is not " + "supported on the current platform"); } sun.awt.AppContext context = sun.awt.AppContext.getAppContext(); Desktop desktop = (Desktop)context.get(Desktop.class); if (desktop == null) { desktop = new Desktop(); context.put(Desktop.class, desktop); } return desktop; }
private static boolean getHeadlessProperty() { if (headless == null) { AccessController.doPrivileged((PrivilegedAction<Void>) () -> { String nm = System.getProperty("java.awt.headless"); if (nm == null) { /* No need to ask for DISPLAY when run in a browser */ if (System.getProperty("javaplugin.version") != null) { headless = defaultHeadless = Boolean.FALSE; } else { String osName = System.getProperty("os.name"); if (osName.contains("OS X") && "sun.awt.HToolkit".equals( System.getProperty("awt.toolkit"))) { headless = defaultHeadless = Boolean.TRUE; } else { final String display = System.getenv("DISPLAY"); headless = defaultHeadless = ("Linux".equals(osName) || "SunOS".equals(osName) || "FreeBSD".equals(osName) || "NetBSD".equals(osName) || "OpenBSD".equals(osName) || "AIX".equals(osName)) && (display == null || display.trim().isEmpty()); } } } else { headless = Boolean.valueOf(nm); } return null; }); } return headless; }
往下排查原因,發現 getHeadlessProperty 方法中 System.getProperty("java.awt.headless") 處獲取系統參數時返回了true。
導致直接拋出了HeadlessException異常。Headless模式是在缺少顯示屏、鍵盤或者鼠標時的系統配置,這是此處的參數導致了無法彈出指定窗口。
System.setProperty("java.awt.headless", "false");
所以需要提前設置參數為false。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。