开发者

Downloading files from Applet

开发者 https://www.devze.com 2023-03-06 02:56 出处:网络
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 th

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 [ActionListeners, SelectionListeners...]. 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).

  1. Use the AppletContext.showDocument(URL,String) method to trigger the download using the browser.
  2. 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.
    1. 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.
    2. 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 a boolean 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.

  1. Pop a JFileChooser to allow the user to decide where to save the File.
  2. If the chooser returns a valid File (indicating the action was not cancelled) proceed with saving.
  3. Get an InputStream from the URL.
  4. Establish an OutputStream to the File.
  5. Read bytes from the InputStream, write them to the OutputStream.
  6. Rinse & repeat till read produces -1.
0

精彩评论

暂无评论...
验证码 换一张
取 消