【问题标题】:javafx 2 webview custom url handler, don't work relative urljavafx 2 webview 自定义 url 处理程序,不工作相对 url
【发布时间】:2013-12-20 18:25:31
【问题描述】:

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

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”这样的相对链接?

【问题讨论】:

    标签: java webview javafx-8


    【解决方案1】:

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

    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");
    

    使用

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

    【讨论】:

    • 您是如何“安装”自定义处理程序的?
    猜你喜欢
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2014-02-23
    • 2023-04-01
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多