Pregunta

my requirement is as follows:

INFO: icefaces upload component, uploads the files to relative folder and creates for each user a sub-directory in that folder with the sessionId.

Requirement: at the sessionDestroyed for each user, i want to get the real path, to delete current user folder.

i know how to get the real path with JSF as follows:

ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
                .getExternalContext().getContext();
        String deploymentDirectoryPath = ctx.getRealPath("/");

Problem: if you try to get the real path in sessionDestroyed you will get null pointer exception, so i was wondering if there's a way to initialize the variable deploymentDirectoryPath in the listener so i can use it in sessionDestroyed method, or maybe initialize the real path variable on application startup and use it here ?

please advise how to solve this issue.

¿Fue útil?

Solución

Even though you haven't posted the actual code that relates to the problem, the following gives me the real path:

public class MySessListener implements HttpSessionListener {

    @Override
    public void sessionCreated(final HttpSessionEvent se) {
        System.out.println(Thread.currentThread().getStackTrace()[1]);
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                HttpSession sess = se.getSession();
                sess.invalidate();
            }
        }, 10000);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println(Thread.currentThread().getStackTrace()[1]);
        String realPath = se.getSession().getServletContext().getRealPath("/");
        System.out.println("realPath: " + realPath);
    }
}

Output

INFO: com.bhesh.demo.web.listener.MySessListener.sessionCreated(MySessListener.java:13)
INFO: com.bhesh.demo.web.listener.MySessListener.sessionDestroyed(MySessListener.java:26)
INFO: realPath: C:\Documents and Settings\Bhesh\My Documents\NetBeansProjects\JsfMessageList\build\web\

Otros consejos

Based on BalusC sound advice here and elsewhere one could write a general purpose function like this:

  String getPath(){

ExternalContext tmpEC;      

tmpEC = FacesContext.getCurrentInstance().getExternalContext();   
String realPath=tmpEC.getRealPath("/");
return realPath;    
}

You can get the real path as follows:-

FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");

EDIT:-

As mentioned by BalusC in one of his answers, you should think twice before using getRealPath("/") because if one has not chose to expand the war file then, getRealPath("/") might return null.

Use getExternalContext.getResourceAsStream instead. as per, docs, It is valid to call this method during application startup or shutdown.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top