I have a Java Applet application. The use case is as follows:
The users invoke a URL which is mapped to a Servlet. The servlet as a response returns a JSP page from which the users can navigate in the UI. The entire UI is made of Swing [basically a JApplet]. The events in the UI are handled in the traditional manner [ActionListener
s, SelectionListener
s...]. Now I have the following requirement:
There is a file in the server directory that I am supposed to allow the users to download through my application. I need to give the users a link in my UI, the clicking of which will trigger the download.
Can this be done 开发者_JS百科considering the security features of JApplets? Also consider the event handling mechanism of Swing components.
The options for a sand-boxed applet.
There are 2(.2) ways to go (that I can immediately think of).
- Use the AppletContext.showDocument(URL,String) method to trigger the download using the browser.
- For 'Next Generation' plug-in 2 based applets (1.6.0_10+ in Sun/Oracle's JVM) it is possible to hook into the functionality of the JNLP API of Java Web Start.
- The JNLP API provides the ability to access the local file-system in a sand-boxed application or applet. Here is my little demo. of the JNLP API file services.
- The JNLP API also provides the BasicService.showDocument(URL) method. This version is slightly superior to the
AppletContext
equivalent for the fact that it returns aboolean
to indicate success/failure. The applet based version might fail, and if it does, it does so silently. See also the demo. of the BasicService.
A trusted applet can use this process.
- Pop a
JFileChooser
to allow the user to decide where to save theFile
. - If the chooser returns a valid
File
(indicating the action was not cancelled) proceed with saving. - Get an
InputStream
from theURL
. - Establish an
OutputStream
to theFile
. - Read bytes from the
InputStream
, write them to theOutputStream
. - Rinse & repeat till read produces -1.
精彩评论