问题
I'm interested What is the proper way to use JSF pages with AJAX when I use CDI.
I tested to configure the CDI beans with @SessionScoped
but I found that there is a problem with AJAX.
Is it proper to use AJAX with CDI beans configured with @ConversationScoped
?
And I found that I have to put conversation.begin();
into the Bean constructor and conversation.end();
into Java method which must be when the session is completed. Can I somehow do this automatically?
P.S Can I use this code to automatically free the resource when the user closes the page?
@Remove
public void finishIt(){
conversation.end();
}
回答1:
And I found that I have to put
conversation.begin();
into the Bean constructor andconversation.end();
into Java method which must be when the session is completed.
That's correct. See also among others How to replace @ManagedBean / @ViewScope by CDI in JSF 2.0/2.1 for a concrete code example.
Can I somehow do this automatically?
If you want a bean which must live as long as you're postbacking on a single view, then upgrade to at least JSF 2.2. It provides a CDI compatible @ViewScoped out the box.
If you however want a bean which must live as long as you reference it in a view, regardless of the view you're sitting in, then consider using @ViewAccessScoped of DeltaSpike instead. Once you navigate to a view which doesn't reference the bean anywhere, it will be trashed.
See also:
- How to choose the right bean scope?
回答2:
By default the Conversation object is in transient state. Invocation of the begin method marks it as long-running (when a real conversation starts). Ending conversation (by invoking end method) marks Conversation object as transient.
A transient conversation scoped bean will live for a life cycle of single request .
long-ending conversation(initiated by conversation.begin) will run unless conversation.end is called.
来源:https://stackoverflow.com/questions/15427217/ajax-pages-with-cdi-beans-and-conversationscoped