javafx 2 webview自定义url处理程序,不工作相对url

use*_*796 1 java webview javafx-8

我有简单的应用程序代码:

webView.getEngine().load("classpath:data/index.html");
Run Code Online (Sandbox Code Playgroud)

自定义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();
    }
}
Run Code Online (Sandbox Code Playgroud)

安装人:

URL.setURLStreamHandlerFactory(protocol -> {
    if(protocol.equals("classpath")) {
        return new Handler();
    } else {
        return null;
    }
});
Run Code Online (Sandbox Code Playgroud)

它加载data/index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
<div>Hello, World!!!</div>
<img src="download.jpg">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但结果图像没有出现.

如何让WebView解析像"download.jpg"这样的相关链接?

use*_*796 5

我瘦了我找到了解决方案:

Handler.openConnection(URL u)我们必须添加

String path = getURL().getPath().startsWith("/") ? getURL().getPath().substring(1) : getURL().getPath();
URL resourceUrl = classLoader.getResource(path);
Run Code Online (Sandbox Code Playgroud)

代替

URL resourceUrl = classLoader.getResource(u.getPath());
Run Code Online (Sandbox Code Playgroud)

而是标准化URL

webView.getEngine().load("classpath:data/index.html");
Run Code Online (Sandbox Code Playgroud)

使用

webView.getEngine().load("classpath:///data/index.html");
Run Code Online (Sandbox Code Playgroud)