My JSF Books/Videos My JSF Tutorials OmniFaces/JSF PPTs
JSF 2.3 Tutorial
JSF Caching Tutorial
JSF Navigation Tutorial
JSF Scopes Tutorial
JSF Page Author Beginner's Guide
OmniFaces 2.3 Tutorial Examples
OmniFaces 2.2 Tutorial Examples
JSF Events Tutorial
OmniFaces Callbacks Usages
JSF State Tutorial
JSF and Design Patterns
JSF 2.3 New Features (2.3-m04)
Introduction to OmniFaces
25+ Reasons to use OmniFaces in JSF
OmniFaces Validators
OmniFaces Converters
JSF Design Patterns
Mastering OmniFaces
Reusable and less-verbose JSF code

My JSF Resources ...

Java EE Guardian
Member of JCG Program
Member MVB DZone
Blog curated on ZEEF
OmniFaces is an utility library for JSF, including PrimeFaces, RichFaces, ICEfaces ...

.

.

.

.

.

.

.

.


[OmniFaces Utilities] - Find the right JSF OmniFaces 2 utilities methods/functions

Search on blog

Petition by Java EE Guardians

Twitter

Se afișează postările cu eticheta state helper. Afișați toate postările
Se afișează postările cu eticheta state helper. Afișați toate postările

vineri, 6 martie 2015

JSF 2.2 - 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 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>

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

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

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

 <hr/>
 Application Scoped Bean:
 <h:outputText value="#{timestampASBean.timestamp}"/>
 <hr/>
</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 as shown in the following screenshot:
The request, session, and application scopes work as expected!

You also may be interested in:

JSF 2.2 support stateless

The notion of being stateless is pretty confusing, because every application must maintain some kind of state (for example, for runtime variables). Generically speaking, a stateless application will follow the rule of a state per request, which means that a state's lifecycle is the same as the request-response lifecycle. This is an important issue in web applications, where we need to use session/application scope that, obviously, breaks down the notion of stateless.
Even so, one of the most popular features of JSF 2.2 consists of stateless views (and is actually available starting with Version 2.1.19). The idea behind this concept assumes that JSF will not save/restore the view state between requests and will prefer to recreate the view state from the XHTML tags on every request. The goal is to seriously increase performances: the gain time used for the save/restore view state, more efficient usage of server memory, more support for clustered environments, and the prevention of ViewExpiredExceptions. So, JSF developers have certain requirements of the stateless feature. Nevertheless, it seems that the stateless feature doesn't affect too much of the time used for saving/restoring the view state (this is not expensive, especially when the state is saved on a server session and is not going to be serialized) and memory performances. On the other hand, when an application is deployed on several computers (in clustered environments), the stateless feature can be a real help because we don't need session replication (refers to replicating the data stored in a session across different instances) and/or sticky sessions (refers to the mechanism used by the load balancer to improve efficiency of persistent sessions in a clustered configuration) anymore. For stateless applications, the nodes do not need to share states, and client postback requests can be resolved by different nodes. This is a big achievement, because in order to resolve many requests, we can add new nodes without worrying about sharing the state. In addition, preventing ViewExpiredException is also a big advantage.

Note Stateless views can be used to postpone session creation or dealing with big (complex) component trees that implies an uncomfortable state.

Starting with JSF 2.2, the developers can choose between saving the view state and creating stateless views in the same application, which means that the application can use dynamic forms in some views (stateful) and create/recreate them for every request in other views (stateless). For a stateless view, the component tree cannot be dynamically generated/changed (for example, JSTL and bindings are not available in the stateless mode) and resubmitting forms will probably not work as expected. Moreover, some of the JSF components are stateful, which will lead to serious issues in a stateless view. But, it is not so easy to nominate those components and the issues, since their behavior is dependent on the environment (context). Some specific tests may be helpful.
In order to write a JSF stateless application, you have to design everything to work only with the request scoped bean. In some cases, we can use different tricks to accomplish this task, like using hidden fields and special request parameters for emulating a session. While session and application beans will break down the idea of stateless (even if it is possible to use), the view bean will act as request beans.

Programmatically speaking, defining a view as stateless is a piece of cake: just add the attribute named, transient to the <f:view> tag and set its value to true. Note that in order to have a stateless view, the presence of <f:view> tag is mandatory, even if it doesn't have any other use. Each stateless view of an application needs this setting because there isn't a global setting for indicating that the stateless effect
should be applied at the application level.

<f:view transient="true">
 ...
</f:view>


When a view is stateless, the javax.faces.ViewState value will be stateless, as shown in the following screenshot:
You also may be interested in:

joi, 5 martie 2015

Server-state serialization in a session

On the server side, the state can be stored as a shallow copy or as a deep copy. In a shallow copy, the state is not serialized in the session (JSF stores only pointers to the state in a session and only the container deals with serialization stuff), which requires less memory and allows you to inject EJBs in the view scoped beans (use this technique carefully, since the changes that affect objects in one copy will be reflected in the rest of the copies). The deep copy represents a full serialization of the state in a session, which requires more memory and doesn't allow injecting EJBs.

Note By default, JSF Mojarra uses shallow copy, while JSF MyFaces uses deep copy. Anyway, perform a quick test to be sure which is the default.

We can easily alter the default behavior by explicitly setting the javax.faces.SERIALIZE_SERVER_STATE context parameter in web.xml. This context parameter was introduced starting with JSF 2.2 and represents the standard context parameter for setting the server state serialization in Mojarra and MyFaces. You can indicate that the shallow copy should be used as follows:

<context-param>
<param-name>javax.faces.SERIALIZE_SERVER_STATE</param-name>
<param-value>false</param-value>
</context-param>

Note In order to avoid exceptions of type, java.io.NotSerializableException (and warnings of type Setting non-serializable attribute value ...), keep in mind that serializing the state in a session implies serializable backing beans. (They import java.io.Serializable and their properties are serializable. Special attention to nested beans, EJBs, streams, JPA entities, connections, and so on.) This is also true when you are storing the view state in the client since the entire state should be serializable. When a bean property should not (or cannot) be serialized, just declare it transient and do not forget that it will be null at deserialization.

In addition to the preceding note, a common case implies java.io.NotSerializableException, when the state is saved on the client. But when switching the state on the server, this exception miraculously disappears on Mojarra, while it is still present in MyFaces. This can be confusing, but is perfectly normal if you are using Mojarra implementation, the state should be fully serializable while saving it on the client (and it is not, since this exception occurred), while this is not true on the server, where Mojarra by default doesn't serialize the state in a session. On the other hand, MyFaces defaults to serialize the state; therefore, the exception persists.

Note Sometimes, you may optimize memory usage and save server resources by redesigning the application state, which contains view or session or application backing beans (don't cache the data that can be queried from a database and try to reduce the number of such beans). Besides managing the view state, this is also an important aspect that reflects directly in performance. When more memory is needed, the container may choose to serialize the parts of the application state, which means that you have to pay the price of deserialization also. While the price of saving in the session is represented by memory, the price of serialization/deserialization is represented by the time and insignificant disk space (at least it should be insignificant).

You also may be interested in:

miercuri, 4 martie 2015

JSF logical and physical views

We know that JSF can store a full or partial view state on server or on client with some advantages and disadvantages. Further, you have to know that JSF differentiates views in logical views (specific to the GET requests) and physical views (specific to the POST requests). Each GET request generates a new logical view. By default, JSF Mojarra (the reference implementation of JSF) manages 15 logical views, but this number can be adjusted through the context parameter, com.sun.faces.numberOfLogicalViews, as shown in the following code:

<context-param>
<param-name>com.sun.faces.numberOfLogicalViews</param-name>
<param-value>2</param-value>
</context-param>

You can easily perform a test of this setting by starting the browser and opening an application three times, in three different browser tabs. Afterwards, come back to the first tab and try to submit the form. You will see a ViewExpiredException because the first logical view was removed from the logical views map, as shown in the following screenshot:


If you open the application in one or two tabs, this error will not occur. There is another story with the POST requests (non-AJAX), because, in this case, JSF (Mojarra implementation) will store every single form in the session until the maximum size is reached. A POST request creates a new physical view (except AJAX requests which use the same physical view repeatedly) and JSF Mojarra can store 15 physical views per logical view (Map<LogicalView, Map<PhysicalView, and ViewState>>). Obviously, a physical view can contain multiple forms.
You can control the number of physical views through the context parameter named com.sun.faces.numberOfViewsInSession. For example, you can decrease its value to 4 as shown in the following code:

<context-param>
<param-name>com.sun.faces.numberOfViewsInSession</param-name>
<param-value>4</param-value>
</context-param>

This small value allows you to perform a quick test. Open an application in the browser and submit a form four times. Afterwards, press the browser's back button four times, to return to the first form and try to submit it again. You will see an exception, because this physical view was removed from the physical view's map. This will not happen if you submit the form less than four times.

Note In case you need more than 15 logical/physical views, then you can increase their number or choose to save the state on the client. Saving the state on the client is recommended since it will totally eliminate this problem.

In case of navigation between pages, JSF doesn't store anything in the session for the GET requests, but will save the state of forms for the POST requests.

You also may be interested in:
JSF saving the view state

JSF saving the view state

Commonly, the JSF applications' performance is directly related to CPU memory, serialization/deserialization tasks, and network bandwidth. When these variables start to become the source of headache, or errors of type ViewExpiredException or NotSerializableException occur, it is time to find out about JSF's managing view state feature and how it can be finely tuned to increase the performance. Therefore, further, we will discuss about JSF saving the view state - JSF's partial saving view state feature and JSF saving the view state on server/client.

JSF saving the view state
First, you have to know that JSF saves and restores the view state between requests using the ViewHandler/StateManager API. JSF does this during its lifecycle, the view state is saved in the session (or on the client machine) at the end of a request and is restored at the beginning of a request.
JSF uses this technique because it needs to preserve the views state over the HTTP protocol, which is a stateless protocol. Since JSF is stateful, it needs to save the state of views in order to perform the JSF lifecycle over multiple requests from the same user. Each page has a view state that acts as a ping-pong ball between the client and the server. A view is basically a component tree that may be dynamically changed (altered) during HTTP GET and POST requests. Each request will successfully go through the JSF lifecycle only if the component tree was previously saved and is fully capable to provide the needed information, that is, Faces Servlet succeeds to call the needed view handler implementations to restore or build the view. So, when the component tree is programmatically changed (for example, from backing beans or static components) it can't be successfully recreated from scratch (or rebuilt). The only solution is to use the existing state saved at the Render Response phase. Trying to recreate it from scratch will make the programmatic changes useless, since they would no longer be available.

Note Keep in mind that the component tree is just a hand of UI components hierarchically and logically related. The view state maintains the tree structure and the components state (selected/deselected, enabled/disabled, and so on). Therefore, the component tree contains only references to backing beans properties/actions through EL expressions, and does not store the model values.

JSF partial saving view state
Starting with JSF 2.0, the performance of managing the state was seriously increased by adding the partial state saving feature. Basically, JSF will not save the entire component tree, only a piece of it. Obviously this will require less memory. In other words, this means that instead of saving the entire component tree (the whole view, <html>), now, for every request during restore view, JSF will recreate the entire component tree from scratch and initialize the components from their tag attributes. In this way, JSF will save only the things that are deserved to be saved. These are the things that are susceptible to changes (for example, <h:form>) that cannot be recreated from scratch and/or represent inland details of components. These details are: dynamic (programmatic) changes that alter the component tree, different kinds of values that were determined for some components (usually at first postback), and values that were changed for components but have not been submitted (for example,
moving a slider or checking a checkbox). On the other hand, the things that cannot be changed by the client will not be saved.

Partial state saving and tree visiting
In JSF 2.0, the JSF partial state saving feature raised a question similar to how a JSF implementation should visit all the components in the component tree and ask them for their state (partial)? The answer in JSF 2.1 (and earlier versions) was specific to this implementation: Mojarra used a tree visiting algorithm, while MyFaces used a so-called "facets + children" traversal. But, technically speaking, these two approaches are pretty different, because Mojarra provides a pluggable algorithm, while MyFaces doesn't. Moreover, the Mojarra approach is in context (before children are visited, the parent component can choose to use a context/scope), while the MyFaces approach follows a pointer design. Furthermore, the Mojarra algorithm can visit virtual components. (These kinds of components are obtained by looping components such as UIData) On the other hand, from the saving state perspective, using a context/scope and looping virtual components is not desirable, even if affecting the visiting process can be major and useful. In order to solve this problem, JSF 2.1 offers some hints, which can be considered deprecated starting with JSF 2.2. Starting with JSF 2.2, tree visiting is fully capable of partial state saving; thanks to the StateManagementStrategy.saveView() and StateManagementStrategy.restoreView() methods. These two methods are meant to replace their counterparts from the StateManager class, and their implementations are now mandatory to use the visit API. (A good point to start studying may be the UIComponent.visitTree() method.) As a JSF developer, you will probably never interact with this feature, but for the sake of completeness, it may be good to be aware of it.

JSF saving view state on the server or client
Saving the view state can be accomplished on the server that hosts the application, or on the client machine. We can easily choose between the client and the server by adding the context parameter named javax.faces.STATE_SAVING_METHOD to the web.xml file. The value of this method can be server or client as shown in the following code:

<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>

Starting with JSF 2.2, the values of this context parameter are case insensitive. Saving the state on the server means to save it in a session with a special ID known as the view state ID that refers to the state stored in the server memory. This is sent to the client as the value of a hidden input field named, javax.faces.ViewState. This can be easily tested by running an application which produces the HTML code that contains this field, as shown in the following screenshot:


If the state is saved on the client, JSF stores it as the value of the same hidden input field. This value is a base64 encrypted string representing the serialization of the state:

Specifying where the view state will be saved is a piece of cake, but choosing between saving the view state on a client or on a server can be a difficult choice, because each has its own advantages and disadvantages. Both have a cost, and everybody wants to pay a lower price. Choosing the client will increase network traffic because the serialized state will generate a larger value for the javax.faces.
ViewState input field. Moreover, encoding/decoding the view state and possible trespasser attacks are also important drawbacks of this approach. On the other hand, the server uses less memory because nothing is stored in the session. Moreover, storing the view state on the client will also be a good solution to prevent losing it when the server is down, and to prevent ViewExpiredException that occurs when the session has expired, or when the maximum number of opened views was reached. Saving the state on the server has an opposite effect: the network traffic is lower, the usage of memory by the server increases, and the server failures will result in loss of the state and possible ViewExpiredException instances.

Note Usually, developers prefer to have a lower network traffic and use more memory on the server, because memory is easy to provide to an application server. But this is not a rule; you just have to think what's cheaper for you. Some heavy benchmarks can also provide compelling indications about storing the state on the client or on the server.

In order to make the right choice, do not forget that JSF 2.0 comes, by default, with partial state saving, which will be reflected in a smaller size of the javax.faces.ViewState input field (the state saved on the client) or in less memory needed (the state saved on the server). You can disable partial state saving by adding the following context parameter in web.xml:

<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>false</param-value>
</context-param>

For a simple visual test, you can choose to save the state on the client and run the same application twice: first time, enable partial state saving, and second time, disable it—the result shown in the following screenshot speaks for itself:


Furthermore, in the same application, you can use partial state saving for some views and full state saving for other views. Skip the javax.faces.PARTIAL_STATE_SAVING context parameter and use the javax.faces.FULL_STATE_SAVING_VIEW_IDS context parameter. The value of this context parameter contains a list of view IDs for which the partial state saving will be disabled. The IDs should be comma separated, as shown in the following code (suppose you have three pages: index.xhtml, done.xhtml, and error.xhtml, partial state saving is used only for index.xhtml):

<context-param>
<param-name>javax.faces.FULL_STATE_SAVING_VIEW_IDS</param-name>
<param-value>/done.xhtml,/error.xhtml</param-value>
</context-param>

Programmatically, you can check if the state is saved on the client as follows:

·         In view/page the code is as follows:
#{facesContext.application.stateManager.isSavingStateInClient(facesContext)}

·         In backing bean, the code is as follows:
FacesContext facesContext = FacesContext.getCurrentInstance();
Application application = facesContext.getApplication();
StateManager stateManager = application.getStateManager();
logger.log(Level.INFO, "Is view state saved on client ? {0}",
stateManager.isSavingStateInClient(facesContext));

You also may be interested in:

JSF BOOKS COLLECTION

Postări populare

Visitors Starting 4 September 2015

Locations of Site Visitors