tags:

views:

36

answers:

2

Hi,

I'm new to the java web world, so forgive me if I say something stupid.

I'm working with struts 2 and I need to delete a file (which is located on the server) when a jsp is closed.

Does any body knows how to do this?

Thanks in advance.

+1  A: 

On window.onunload call, using ajax, an action that deletes the file.

Bozho
+4  A: 

The window.onunload suggestion is nice, but there is no guarantee that the ajax request will ever hit the server. As far as I recall, only certain IE versions with certain configurations will send the ajax request successfully. Firefox and others won't do that. And then I don't talk about the cases when the user has JS disabled.

You don't want to rely on that. Rather hook on the session expiration. You can do that with help of HttpSessionListener or maybe HttpSessionBindingListener when it concerns an (existing) attribute of the session.

E.g.

public class CleanupSession implements HttpSessionListener {

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        new File(somePath).delete();
    }

    // ...
}

(register it in web.xml as a <listener>)

Or, in case of an "logged-in user" example (which is stored in the session scope):

public void User implements HttpSessionBindingListener {

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        new File(somePath).delete();
    }

    // ...
}
BalusC
Sorry can't vote you yet, but thanks, will give it a try!
Ecarrion
You're welcome. Keep in mind that the session will not be immediately expred when the browser window/tab is closed. It'll last by default 30 minutes thereafter. But it's at least the most robust way to ensure the file being deleted.
BalusC
The file I need to delete depends of the user, and since I have to define a new class I'm having problems telling the method what file delete.
Ecarrion
You could make it a property of the `User` class. The `User` class should of course represent the logged-in user. All with all, you basically need to store a reference to the `File` (in)directly in the session.
BalusC