2013-12-20 13 views
1

我有簡單的應用程序與代碼:的JavaFX 2的WebView自定義的處理器,不工作相對URL

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」?

回答

5

我瘦我找到了解決辦法:

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

和standartize網址,而不是

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

ü se

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

你是如何「安裝」自定義處理程序的? –