How to get real path in JSF in a SessionListener

Mahmoud Saleh picture Mahmoud Saleh · Nov 26, 2011 · Viewed 7.3k times · Source

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.

Answer

Bhesh Gurung picture Bhesh Gurung · Nov 26, 2011

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\