How to reach css and image files from the html pag

2020-02-07 01:13发布

I have a String HTML content which is loaded into webEngine by loadContent() method. I have also some css and image files used in this page. Although I put these file into the same package of java class, the loaded page cannot find them. Looked for API docs and web, but could not find any appropiate similar solutions. How I load these files?

4条回答
唯我独甜
2楼-- · 2020-02-07 01:54

I just found out that using the <base> tag in the HTML also does the trick:

<html>
    <head>
        <title>The slash at the end of the href is important!</title>
        <base href="file:///absolute/path/to/your/docroot/" />
    </head>
    <body>
        <img src="image.png"/>
    </body>
</html>

If you load the above code via engine.loadContent(String) then image.png will be loaded from /absolute/path/to/your/docroot/image.png.

This method is easier if you need to load multiple resources since you only have to specify the absolute path at a single place.

This has been tested with WebView of Java 8u25.

查看更多
\"骚年 ilove
3楼-- · 2020-02-07 02:09

You can place your string html content in a file in the same package as the Java class and use the engine.load(String url) method instead:

engine.load(getClass().getResource("mypage.html").toExternalForm());

When you do this, all relative links in the html page will resolve to resources (e.g. css and image files) in your Java package.

Beware that if you are loading a resource that is located in a jar file, that the jar: protocol does not understand relative links with parent specifiers. E.g., <img src="../images/image.png"/> will not work, but <img src="/images/image.png"/> or <img src="images/image.png"/> will as long (as you put the image in the appropriate location in the jar file). The file: protocol does not have such restrictions and .. relative links will work fine when the resources are loaded using it.

If the html string is dynamically generated by your java code rather than static, then Sergey's solution is probably best.

查看更多
爷的心禁止访问
4楼-- · 2020-02-07 02:13

You need to set your local paths in html string for loadContent next way:

view.getEngine().loadContent(
"<img src='" + getClass().getResource("1.jpg") + "' />");
查看更多
何必那么认真
5楼-- · 2020-02-07 02:15

Try this

<link href="file:css\default.css" rel="stylesheet" type="text/css" />
查看更多
登录 后发表回答