Minimizing the JSF ViewState for large page - performance

I'm currently developing a JSF application with single-page-per-app design, such like in desktop apps. the sections are placed in tabs, and every suboperation, such as editing or inserting item, in displayed in dialog.
What is becoming the issue, it is both the size of ViewState and the processing time of each request. At the moment, the initial size of ViewState in POST is 200kb (and the compression is enabled). The request last from 200 to 400 ms (on my own machine, with no users except me).
Setting state saving to session greatly reduces the request, but greatly increases the processing time - now it's from 350 to 600 ms. Because this is intranet application, net transfer is cheap, so better to send more that process longer.
I don't know how to deal with that problem. Is it possible to reduce the space consumed by JSF components? Most of them don't change on every click, but they seem to be deserialized and processed anyway. Or should I throw out every data (such as dictionaries for drop-down lists) from JSF beans and use intensive caching in service layer? Or there are other options/tricks/improvements I could use?

As you have already figured out, the View State of the entire form is being serialized on every ansynchronous post back so that the server and client can stay in sync. ASP.NET works in pretty much the exact same way.
The Primefaces team has added functionality to many of their Ajax enabled components that allow for Partial Page posts.
http://blog.primefaces.org/?p=1842
The partialSubmit property will only serialize form elements that are specified in the process attribute of the component or <p:ajax>. Of course this is only a solution for Primefaces components, but it has significantly reduced the request size on some of my larger JSF pages.

You can utilize IFrames and session variables to reduce component trees. Each iframe will maintains its own view. Of course in back end process your application is no longer a single page application. However user will still seamlessly see it as a single age applications.

Related

What is the limit of holding the data in viewstate?

What is the limit of data we hold in ViewState? And are the limitations of Viewstate?
ViewState["allDataOfCandidates"]=dt;
Regards,
Ganesh.
http://www.twitter.com/ganeshatkale
Viewstate does not have any size limitations. But nothing comes for free, and view state is no exception. It certainly imposes performance hits whenever an Asp.net webpage is requested.
On all page visits, during the save view state stage the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __VIEWSTATE form filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.
The __VIEWSTATE hidden form field adds extra size to the Web page that the client must download. For some view state-heavy pages, this can be tens of kilobytes of data, which can require several extra seconds (or minutes!) for modem users to download. Also, when posting back, the __VIEWSTATE form field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time.
If you are designing a Web site that is commonly accessed by users coming over a modem connection, you should be particularly concerned with the bloat the view state might add to a page. Fortunately, there are a number of techniques that can be employed to reduce view state size. You just have to turn off the view state tracking for that control.
For additional information you can go through - https://msdn.microsoft.com/en-us/library/ms972976.aspx

Handling forms with many fields

I have a very large webform that is the center of my Yii web application. The form actually consists of multiple html form elements, many of which are loaded via AJAX as needed.
Because of the form's size and complexity, having multiple save or submit buttons isn't really feasible. I would rather update each field in the database as it is edited by asynchrously AJAXing the new value to the server using jeditable or jeditable-like functionality.
Has anyone done anything like this? In theory I'm thinking I could set up an AJAX endpoint and have each control pass in its name, its new value, and the CRUD operation you want to perform. Then the endpoint can route the request appropriately based on some kind of map and return the product. It just seems like someone has to have solved this problem before and I don't want to waste hours reinventing the wheel.
Your thoughts on architecture/implementation are appreciated, thanks for your time.
In similar situation I decided to use CActiveForm only for easy validation by Yii standarts (it can use Ajax validation), avoiding "required" attribute. And of course to keep logical structure of the form in a good view.
In common you're right. I manually used jQuery to generate AJAX-request (and any other actions) to the controller and process them there as you want.
So you may use CRUD in controller (analyzing parameters in requests) and in your custom jQuery (using group selectors), but you can hardly do it in CActiveForm directly (and it's good: compacting mustn't always beat the logic and structure of models).
Any composite solution with javascript in PHP will affect on flexibility of your non-trivial application.
After sleeping on it last night, I found this post:
jQuery focus/blur on form, not individual inputs
I'm using a modified version of this at the client to update each form via AJAX, instead of updating each field. Each form automatically submits its data after a two seconds of inactivity. The downside is the client might lose some data if their browser crashes, but the benefit is I can mostly use Yii's built-in controller actions and I don't have to write a lot of custom PHP. Since my forms are small, but there are many of them, it seems to be working well so far.
Thanks Alexander for your excellent input and thanks Afnan for your help :)

Wicket and complex Ajax scenarios

When a screen has multiple interacting Ajax controls and you want to control the visibility of components to react to these controls (so that you only display what makes sense in any given situation), calling target.addComponent() manually on everything you want to update is getting cumbersome and isn't very maintainable.
Eventually the web of onClick and onUpdate callbacks can reach a point where adding a new component to the screen is getting much harder than it's supposed to be.
What are the commonly used strategies (or even libraries if such a thing exists) to avoid this build-up of complexity?
Update: Thank you for your answers, I found all of them very useful, but I can only accept one. Sorry.
In Wicket 1.5 there is an event bus. Each component has onEvent(Object payload) method. With component.send() you can broadcast events and each component can check the payload (e.g. UserJoinedEvent object) and decide whether it wants to participate in the current Ajax response. See http://www.wicket-library.com/wicket-examples/events/ for a simple demo.
You could add structural components such as WebMarkupContainers, when you add this to the AjaxTarget everything contained in it will also get updated. This allows you to update groups of components in a single line.
When I'm creating components for a page I tend to add them to component arrays:
Component[] pageComponents = {
new TextField<String>("Field1"),
new TextField<String>("Field2"),
new TextField<String>("Field3")
}
As of Wicket 1.5 the add functions take array parameters [1]. Therefore elements can be added to the page or target like this:
add(pageComponents);
target.add(pageComponents);
Components can then be grouped based on which you want to refresh together.
[1] http://www.jarvana.com/jarvana/view/org/apache/wicket/wicket/1.5-M3/wicket-1.5-M3-javadoc.jar!/org/apache/wicket/ajax/AjaxRequestTarget.html
Well, of how many components do we speak here? Ten? Twenty? Hundreds?
For up to twenty or about this you can have a state controller which controls which components should be shown. This controller sets the visible field of a components model and you do always add all components to your requests which are handled by the controller. The components ajax events you simply redirect to the controller handle method.
For really large numbers of components which have a too heavy payload for a good performance you could use javascript libraries like jQuery to do the show and hide things by the client.
I currently use some sort of modified Observer-Pattern to simulate an event-bus in Wicket 1.4.
My Pages act as an observable observer since my components don't know each other and are reused in different combinations across multiple pages. Whenever one component receives an Ajax-event that could affect other components as well, it calls a method on it's page with an event-object and the ajax-target. The page calls a similar method on all components which have registered themselves for this kind of event and each component can decide, on the base of the supplied event-object if and how it has to react and can attach itself to the target.
The same can be archived by using the wicket visitor. I don't know which one is better, but I think that's mainly a matter of taste.

uicomponent tree memory usage

Greetings,
I have rich faces application (3.3.2.SR1). The application uses ModelPanel to view entities. All modal panels are not rendered until I want to show them (rendered = false). Application becomes to be big, and uses a lot relations from one panel to others. All works fine, but it looks like richfaces creates UIComponent tree in memory for all possible cases if component rendred is true or false. When I tried to check memory usage of application (I used YourKit Java Profiler for these needs) I see that it uses a lot of memory for one session.
I am using Facelets together with richfaces and I tried to use
<c:if test="rendred condition"... /> content </c:if>
It starts to use significantly less memory, but...
when I rerender the area with panel, controls on parent screen are stopped to work. I suspect that it is because of every time when component tree is changed it recreates whole tree, and I have unsynchronized client (html) and server (faces) parts.
Could somebody suggest me the way how to reduce memory usage? I have real problem with it as StandardSession object in HeapMemory uses 60-150Mb. And almost all of this memory used for UIControls.
Example of the problem:
I have page which has references to panel1, panel2, panel3.
Panel is:
<rich:modalPanel >
<a4j:outputPanel layout="block"
rendered="#{PanelBeanHolder.renderedViewScreen}">
<ui:insert name="panelContent" />
</a4j:outputPanel>
</rich:modalPanel>
I am rendering panel only when action for this is performed. And do not want to load the UI controls for output panel until I need it.
Thank you in advance.
P.S. I tried to do the following to improve the situation
Configure number of views in session inside web.xml with:
<context-param>
<param-name>com.sun.faces.numberOfViewsInSession</param-name>
<param-value>4</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.numberOfLogicalViews</param-name>
<param-value>4</param-value>
</context-param>
It has to improve StateHolder object, but it doesn't help a lot. I did measuring and memory usage is grows when these number are grow. But, when i tired to set them to 1,1 - some pages stopped work. Sometimes request is forwarded to the welcome page. 2,2 improved the situation, but the issue with forwarding to welcome pages still happens.
Tried to use client mode in javax.faces.STATE_SAVING_METHOD. It still uses a lot of memory for UIComponent model. Even if objects are serialised and have to be stored in the form.
Tried to rewrite stateManager
in faces.config:
<state-manager>org.ajax4jsf.application.CompressAjaxStateManager</state-manager>
and rewrite buildViewState and restoreView for compressing the stream.
It doesn't help a lot.
JSF uses a stateful component tree that is maintained between requests. By default, this is usually maintained in the session. There are features you can use to control this.
Configure state saving parameters
There are usually implementation-specific parameters to control the number of views stored in the session - depending on how your application behaves, this might be an easy win.
You can save the state in forms using the javax.faces.STATE_SAVING_METHOD parameter. However, be aware you're sending more information per request and there are security risks in allowing the client to dictate server-side state (ensure you are happy with how your implementation encrypts this data). You will need to check compatibility with your component libraries (i.e. RichFaces), especially if you're using AJAX.
JSF 2 uses a new state-saving mechanism that reduces the session overhead; your faces-config.xml will need to be updated to the 2.0 version. I believe this idea came from Apache Trinidad, so you may be able to extract a pre-JSF 2 version from there.
Do your own state saving and/or view creation
Implementing your own StateManager and/or ViewHandler lets you take programmatic control over how views are handled. For example, you could write a StateManager that persisted views to a database (with appropriate time-out and clean-up).
Use component binding and transient controls
You can take programmatic control over how components are created. From the spec on binding:
When a component instance is first created (typically by virtue of being referenced by a UIComponentELTag in a JSP page), the JSF implementation will retrieve the ValueExpression for the name binding, and call getValue() on it. If this call returns a non-null UIComponent value (because the JavaBean programmatically instantiated and configured a component already), that instance will be added to the component tree that is being created. If the call returns null, a new component instance will be created, added to the component tree, and setValue() will be called on the ValueExpression (which will cause the property on the JavaBean to be set to the newly created component instance).
When a component tree is recreated during the Restore View phase of the request processing lifecycle, for each component that has a ValueExpression associated with the name “binding”, setValue() will be called on it, passing the recreated component instance.
You could probably use this with the transient property on children to control programmatically control creation/destruction of child components. This is manual and a bit messy, but might work in extreme cases.
I'm sure this isn't an exhaustive list.

Best practice for combining requests with possible different return types

Background
I'm working on a web application utilizing AJAX to fetch content/data and what have you - nothing out of the ordinary.
On the server-side certain events can happen that the client-side JavaScript framework needs to be notified about and vice versa. These events are not always related to the users immediate actions. It is not an option to wait for the next page refresh to include them in the document or to stick them in some hidden fields because the user might never submit a form.
Right now it is design in such a way that events to and from the server are riding a long with the users requests. For instance if the user clicks a 'view details' link this would fire a request to the server to fetch some HTML or JSON with details about the clicked item. Along with this request or rather the response, a server-side (invoked) event will return with the content.
Question/issue 1:
I'm unsure how to control the queue of events going to the server. They can ride along with user invoked events, but what if these does not occur, the events will get lost. I imagine having a timer setup up to send these events to the server in the case the user does not perform some action. What do you think?
Question/issue 2:
With regards to the responds, some being requested as HTML some as JSON it is a bit tricky as I would have to somehow wrap al this data for allow for both formalized (and unrelated) events and perhaps HTML content, depending on the request, to return to the client. Any suggestions? anything I should be away about, for instance returning HTML content wrapped in a JSON bundle?
Update:
Do you know of any framework that uses an approach like this, that I can look at for inspiration (that is a framework that wraps events/requests in a package along with data)?
I am tackling a similar problem to yours at the moment. On your first question, I was thinking of implementing some sort of timer on the client side that makes an asycnhronous call for the content on expiry.
On your second question, I normaly just return JSON representing the data I need, and then present it by manipulating the Document model. I prefer to keep things consistent.
As for best practices, I cant say for sure that what I am doing is or complies to any best practice, but it works for our present requirement.
You might want to also consider the performance impact of having multiple clients making asynchrounous calls to your web server at regular intervals.

Resources