marți, 29 decembrie 2015

JSF 2.2 [usage pitfall] - the view scoped beans and the stateless feature

In a stateless environment, the view scoped beans act as request scoped beans. Besides the fact that you can't create/manipulate views dynamically, this is one of the big disadvantages that comes with the stateless feature, because it will affect AJAX-based applications that usually use view scoped beans. You can easily test this behavior with a set of beans with different scopes. The view scoped bean can be defined as follows:

@Named
@ViewScoped
public class TimestampVSBean implements Serializable{

 private static final long serialVersionUID = 1L;

 private Timestamp timestamp;

 public TimestampVSBean() {
  java.util.Date date = new java.util.Date();
  timestamp = new Timestamp(date.getTime());
 }

 public Timestamp getTimestamp() {
  return timestamp;
 }

 public void setTimestamp(Timestamp timestamp) {
 this.timestamp = timestamp;
 }
}

Just change the scope to request, session, and application to obtain the other three beans.
Next, we will write a simple stateless view as follows:

<f:view transient="true">
 <h:form>
  <h:commandButton value="Generate Timestamp"/>
 </h:form>

 Request Scoped Bean:
 <h:outputText value="#{timestampRSBean.timestamp}"/>

 View Scoped Bean:
 <h:outputText value="#{timestampVSBean.timestamp}"/>
 [keep an eye on this in stateless mode]

 Session Scoped Bean:
 <h:outputText value="#{timestampSSBean.timestamp}"/>

 Application Scoped Bean:
 <h:outputText value="#{timestampASBean.timestamp}"/>
</f:view>

Afterwards, just submit this form several times (click on the Generate Timestamp button) and notice that the timestamp generated by the view scoped bean changes at every request. This is a JSF pitfall!

The request, session, and application scopes work as expected!

Niciun comentariu:

Trimiteți un comentariu