JavaFX2 webview自定义url处理程序,don';t工作相对url
我有一个带有代码的简单应用程序:JavaFX2 webview自定义url处理程序,don';t工作相对url,java,webview,javafx-8,Java,Webview,Javafx 8,我有一个带有代码的简单应用程序: webView.getEngine().load("classpath:data/index.html"); 自定义URLStreamHandler: public class Handler extends URLStreamHandler { private final ClassLoader classLoader; public Handler() { this.classLoader = getClass().get
webView.getEngine().load("classpath:data/index.html");
自定义URLStreamHandler:
public class Handler extends URLStreamHandler {
private final ClassLoader classLoader;
public Handler() {
this.classLoader = getClass().getClassLoader();
}
public Handler(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
URL resourceUrl = classLoader.getResource(u.getPath());
if(resourceUrl == null)
throw new IOException("Resource not found: " + u);
return resourceUrl.openConnection();
}
}
安装人:
URL.setURLStreamHandlerFactory(protocol -> {
if(protocol.equals("classpath")) {
return new Handler();
} else {
return null;
}
});
它加载数据/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div>Hello, World!!!</div>
<img src="download.jpg">
</body>
</html>
试验
你好,世界!!!
但结果中的图像并没有出现
如何允许WebView解析诸如“download.jpg”之类的相对链接?我发现了解决方案: 在
Handler.openConnection(URL u)
中,我们必须添加
String path = getURL().getPath().startsWith("/") ? getURL().getPath().substring(1) : getURL().getPath();
URL resourceUrl = classLoader.getResource(path);
而不是
URL resourceUrl = classLoader.getResource(u.getPath());
并将URL标准化
webView.getEngine().load("classpath:data/index.html");
使用
我发现了解决方案: 在
Handler.openConnection(URL u)
中,我们必须添加
String path = getURL().getPath().startsWith("/") ? getURL().getPath().substring(1) : getURL().getPath();
URL resourceUrl = classLoader.getResource(path);
而不是
URL resourceUrl = classLoader.getResource(u.getPath());
并将URL标准化
webView.getEngine().load("classpath:data/index.html");
使用
如何“安装”自定义处理程序?如何“安装”自定义处理程序?