jsf-2.2servletcontextlistenerfacescontext

FacesContext in a @WebListener


I need build some jsf urls in a @WebListener.

I thought I could use a snippet of code like this one

    final FacesContext currentInstance = FacesContext.getCurrentInstance();
    final String actionURL = currentInstance.getApplication().getViewHandler()
            .getActionURL(currentInstance, viewId);

because the javadoc of the .getCurrentInstance() asserts it can be "[...] called during application initialization or shutdown" but it doesn't work because it returns null.

Do I miss somenthing? Any other way to build a url given the viewId?

Thanks


Solution

  • The FacesContext.getCurrentInstance() method does return a valid facesContext instance between the linstener (com.sun.faces.config.ConfigureListener in my case) initialization and the first run of the FacesServlet, in which the facesContext set up by the listener is released. My problem was I was letting Wildfly add the listener and it was added just after mine. Forcing its loading in the web-fragment.xml/web.xml

    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.company.project.somepackages.Listener</listener-class>
    </listener>
    

    let my listener have the context initialized.

    That code above however didn't work because the viewHandler when tries to resolve the contextPath uses the externalContext.getRequestContextPath() method, that obviously returns null, and not the externalContext.getApplicationContextPath() that could return the correct value.