jsf – FacesContext. Getcurrentinstance() returns null in the runnable class

I tried to call FacesContext. in the run () method of the Runnable class. Getcurrentinstance() to get facescontext, but it returns null

public class Task implements Runnable {

    @Override
    public void run() {
        FacesContext context = FacesContext.getCurrentInstance(); // null!
        // ...
    }

}

How did this happen and how should I solve it?

Solution

Facescontext is stored as a ThreadLocal variable in the thread responsible for calling the HTTP request of facesservlet, which is responsible for creating facescontext This thread usually manages bean methods only through JSF Facescontext is not available in other threads generated by this thread

In fact, you should and don't need to use it in other threads In addition, when your thread starts and runs independently, the underlying HTTP request will immediately continue to process the HTTP response and then disappear In any case, you will not be able to perform some operations using HTTP responses

You need to solve your problem in different ways Ask yourself: what do you need? Get some information? Just pass this information to runnable during the build process

The following example assumes that you want to access a session scope object in a thread

public class Task implements Runnable {

    private Work work;

    public Task(Work work) {
        this.work = work;
    }

    @Override
    public void run() {
        // Just use work.
    }

}
Work work = (Work) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("work");
Task task = new Task(work);
// ...

However, if you eventually need to notify the customer that the thread's work has been completed, then you should look for a different way to add a facial message The answer is to use "push" This can be achieved through SSE or WebSockets Specific examples of WebSockets can be found in this related problem: real time updates from database using JSF / Java EE If you happen to use primefaces, check < p: push > If you happen to use omnifaces, check out < o: socket >

Regardless of the specific problem, it is shocking to manually create runnables and manually generate threads in Java EE web applications Go to Q & A below to learn all warnings and how to actually complete them:

> Spawning threads in a JSF managed bean for scheduled tasks using a timer > Is it safe to start a new thread in a JSF managed bean?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>