For start let's see a brief timeline of destroying view scoped beans:
In order to have a quick example I've wrote two view scoped beans. The
first one uses CDI view scope (javax.faces.view.ViewScoped),
and the second one uses OmniFaces 2.2 view scope (org.omnifaces.cdi.ViewScoped). For each of these
beans, I've provide a @PostConstruct method, and, of course, a @PreDestroy method.
JSF view scoped bean:
import javax.faces.view.ViewScoped;
...
@Named(value="jsfViewScoped")
@ViewScoped
public class
JSFViewScopedBean implements Serializable {
private static final Logger LOG =
Logger.getLogger(JSFViewScopedBean.class.getName());
public JSFViewScopedBean() {
}
@PostConstruct
public void init(){
LOG.info("JSFViewScopedBean#init()
invoked ...");
}
public void action() {
LOG.info("JSFViewScopedBean#action()
invoked ...");
}
@PreDestroy
public void destroy() {
LOG.info("JSFViewScopedBean#destroy() invoked ...");
}
}
OmniFaces view scoped bean:
import org.omnifaces.cdi.ViewScoped;
...
@Named(value="omnifacesViewScoped")
@ViewScoped
public class
OmniFacesViewScopedBean implements Serializable {
private static final Logger LOG =
Logger.getLogger(OmniFacesViewScopedBean.class.getName());
public OmniFacesViewScopedBean() {
}
@PostConstruct
public void init(){
LOG.info("OmniFacesViewScopedBean#init()
invoked ...");
}
public void action() {
LOG.info("OmniFacesViewScopedBean#action() invoked ...");
}
@PreDestroy
public void destroy() {
LOG.info("OmniFacesViewScopedBean#destroy() invoked ...");
}
}
In order to simulate some user interaction with these beans, we can
simply write a form with two buttons and a link. One button will invoke JSFViewScopedBean#action(),
and the other one will invoke OmniFacesViewScopedBean#action():
<h:form>
<h:commandButton value="JSF View
Scoped Bean" action="#{jsfViewScoped.action()}"/>
<h:commandButton value="OmniFaces View
Scoped Bean" action="#{omnifacesViewScoped.action()}"/>
</h:form>
<h:link
outcome="done">Done</h:link>
Suppose that we press once each button. This will reveal the following
log:
JSFViewScopedBean#init()
invoked ...
JSFViewScopedBean#action()
invoked ...
OmniFacesViewScopedBean#init()
invoked ...
OmniFacesViewScopedBean#action()
invoked ...
So far, both scopes acts the
same!
Suppose that we press again once each button. This will reveal the
following log:
JSFViewScopedBean#action()
invoked ...
OmniFacesViewScopedBean#action()
invoked ...
So far, both scopes acts the
same!
Finally, suppose that we close the browser or the window/tab or simply
press the Done
link. This will reveal the following log:
OmniFacesViewScopedBean#destroy()
invoked ...
Bingo! Notice that the OmniFacesViewScopedBean
was destroyed immediately when one of these actions took place. The JSFViewScopedBean wasn't
destroyed yet. This will happen when the session expire.
The complete application is available here.
Niciun comentariu :
Trimiteți un comentariu