javafx 2 webview 自定义 url 处理程序,不工作相对 url [英] javafx 2 webview custom url handler, don't work relative url

查看:17
本文介绍了javafx 2 webview 自定义 url 处理程序,不工作相对 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带代码的简单应用:

I have simple app with code:

webView.getEngine().load("classpath:data/index.html");

自定义 URLStreamHandler:

Custom 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:

It load data/index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
<div>Hello, World!!!</div>
<img src="download.jpg">
</body>
</html>

但在结果图像中没有出现.

but in result image doesn't appears.

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

What to do to allow WebView resolve relative link like "download.jpg"?

推荐答案

我觉得我找到了解决方案:

I thin I found the solution:

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,而不是

and to standartize URL, instead

webView.getEngine().load("classpath:data/index.html");

使用

webView.getEngine().load("classpath:///data/index.html");

这篇关于javafx 2 webview 自定义 url 处理程序,不工作相对 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆