用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。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。