Is it possible/how to embed and access HTML Files in a JAR?
File manual = new File(getClass().getResource("/manual/help.html").toURI());
That is where it goes wrong. Java cannot create a File
object from an embedded-resource
Keep it as an URL
and use that for setPage(..)
.
As to the more general problem.
HTML from a Jar file that links resources (e.g. CSS or images) by relative references will work just fine.
E.G.
This example loads HTML (that has a relative reference to an image) from a Jar.
import javax.swing.*;
import java.net.URL;
class ShowHtml {
public static void main(String[] args) {
final String address =
"jar:http://pscode.org/jh/hs/object.jar!/popup_contents.html";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
URL url = new URL(address);
JEditorPane jep = new JEditorPane(url);
JFrame f = new JFrame("Show HTML in Jar");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(jep));
f.pack();
f.setSize(400,300);
f.setLocationByPlatform(true);
f.setVisible(true);
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
}
Screenshot
HTML
The HTML that is being loaded.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<!--
* Copyright (C) 1997 Sun Microsystems, Inc
* All rights reserved.
* Notice of copyright on this source code
* product does not indicate publication.
*
* RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by
* the U.S. Government is subject to restrictions as set forth
* in subparagraph (c)(1)(ii) of the Rights in Technical Data
* and Computer Software Clause at DFARS 252.227-7013 (Oct. 1988)
* and FAR 52.227-19 (c) (June 1987).
*
* Sun Microsystems, Inc., 2550 Garcia Avenue,
* Mountain View, California 94043.
*
-->
<HTML>
<HEAD>
<TITLE>
Editing Project Attributes
</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffff">
<IMG SRC="images/popup_icon.gif" width="24" height="24"> <b>Popup Window</b>
<p>
Popup windows appear near the location from which they are
activated. They are not contained in frames and thus
cannot be resized or moved by the user. Popups are
dismissed by clicking anywhere in the help viewer.
<p>
Popup windows can be activated by clicking on a text object,
graphic object, or JComponent button. All three examples are
included in this demo.
<p>
<A HREF="popup_contents2.html">More...</A>
</body>
</html>
E.G. 2
For dynamically created HTML, the JRE will probably use the class file's location as the presumed location of the HTML. But to remove all doubt, we can specify the base
element in the head
.
import javax.swing.*;
class HtmlUsingBase {
public static void main(String[] args) {
final String htmlContent =
"<html>" +
"<head>" +
"<base href='http://www.gravatar.com/'>" +
"</head>" +
"<body>" +
"<h1>Image path from BASE</h1>" +
"<img src='avatar/a1ab0af4997654345d7a9" +
"49877f8037e?s=128&d=identicon&r=PG'" +
" width='128' height='128'>" +
"</body>" +
"</html>";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel label = new JLabel(htmlContent);
JOptionPane.showMessageDialog(null, label);
}
});
}
}
Screenshot
Embed HTML in JAR with Eclipse
I was using the Package required libraries into generated JAR
, but I had to use Extract required libraries into generated JAR
. I don't know why yet.
When I used the Package
method, java used to look for style.css
in the root of the JAR file, no matter where the HTML file was located.
How to get embedded Jetty serving html files from a Jar, not a War
You need to set the Resource Base for the Context to the URL/URI to where your static content can be accessed from.
Note: you set this at the ServletContext
level, not the DefaultServlet
level, that way all servlets in your context have access to the same information and the various methods in ServletContext
related to real file paths and resources are sane.
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
// Figure out what path to serve content from
ClassLoader cl = MyEmbeddedJettyMain.class.getClassLoader();
// We look for a file, as ClassLoader.getResource() is not
// designed to look for directories (we resolve the directory later)
URL f = cl.getResource("static-root/hello.html");
if (f == null)
{
throw new RuntimeException("Unable to find resource directory");
}
// Resolve file to directory
URI webRootUri = f.toURI().resolve("./").normalize();
System.err.println("WebRoot is " + webRootUri);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setBaseResource(Resource.newResource(webRootUri));
context.setWelcomeFiles(new String[]{"welcome.html"});
ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
holderPwd.setInitParameter("dirAllowed","true");
context.addServlet(holderPwd,"/");
server.setHandler(context);
server.start();
server.join();
}
Open an HTML File Inside a .JAR File
You'll have to devompress the file first.
Something like:
public static void main(String[] args) throws IOException, URISyntaxException {
URL url = Snake.class.getResource("/WebContent/snake.html");
File temp = File.createTempfile();
temp.deleteOnExit();
// Copy content
Desktop.getDesktop().browse(temp.getAbsolutePath());
}
How can I add policy file to the jar applet which is embedded in html file
If your HTML could insert a policy file like that to my machine, it would be an huge security bug. Fortunately, to the best of my knowledge, it is not possible.
If an applet needs trust, digitally sign it.
Related Topics
Aes Gets Different Results in iOS (Obj-C) and Android (Java)
Fatal Signal 11 (Sigsegv) at 0X00000000 (Code=1) - Phonegap
Cordova Could Not Reserve Enough Space for 2097152Kb Object Heap
Android - Copy Assets to Internal Storage
Android What Is Wrong with Openfileoutput
How to Pass Values Between a Dialog and an Activity
How to Fetch Android Market Data When There Is No API
Recyclerview Not Call Oncreateviewholder
Requestlegacyexternalstorage Is Not Working in Android 11 - API 30
Writing Pcm Recorded Data into a .Wav File (Java Android)
Can't Get Okhttp's Response.Body.Tostring() to Return a String
How to Make an Array of Arrays in Java
Does Java Casting Introduce Overhead? Why