Thursday, April 12, 2007

Reset method of FormBeans in Struts

We all know that FormBeans in Struts can have either a 'request' scope or a 'session' scope.

In earlier versions of Struts, I recollect that the reset method of the FormBean was called by the Struts framework whenever the scope is request and not called for session scope. This was because, for 'Request' scope, a pool of FormBean objects were created.

But with new versions of JDK (especially since JDK1.4) object creation is no longer a performance penalty. In fact, short-lived objects are quickly garbage collected because they are allocated in the younger generation of the heap.

Looking at the latest Struts source code (v1.9), I saw that if the scope of the FormBean is Request, then a new FormBean object is created for each request.

Also the reset method is called for both request and session scope FormBeans.
But there is an important difference - if the scope is request, then the constructor of the formbean is also called everytime (for each request), where as for session scope the constructor would be called only once.

So, now what to do? The default reset method does nothing. We only need to override it in the following cases:

1. There are checkboxes and form-bean scope is session: In the reset method we need to reset the checkbox fields, because the browser does not submit a checkbox value if it is clear.

2. Nested beans, arrayLists are used and scope is request: In this case, we need to create a arrayList with the correct size.