標籤:name dac sse 指定 isp ima text vat ppc
用Spring boot搭建項目時,希望在項目啟動完後能自動談出首頁。
就用了java.awt.Desktop類
if (Desktop.isDesktopSupported()) { try { // 彈出瀏覽器 - 顯示HTTP介面(https) Desktop.getDesktop().browse(new URI("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。
Java awt Desktop 無法調用系統瀏覽器