11

Is it possible to keep a request scoped bean alive across postbacks on the same page?

The general problem is, as the bean gets trashed on end of request and recreated on every form submit, for example the booleans behind dynamically manipulated disabled, readonly and rendered get reset to their default values and cause the forms to not work as intented anymore.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Chris
  • 111
  • 1
  • 4

2 Answers2

16

I'll assume that the session scope is not an option, otherwise this question makes little sense.

You can do it using Tomahawk <t:saveState>. Add the following line somewhere to the page:

<t:saveState value="#{bean}" />

RichFaces <a4j:keepAlive> does also the same:

<a4j:keepAlive beanName="#{bean}" />

Or if there is room, upgrade to at least JSF 2.x and put the bean in view scope:

@ManagedBean
@ViewScoped
public class Bean implements Serializable {
    // ...
}

Regardless of the way, the same bean will be there when you postback to the same view and keep returning null or void from action methods.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 2
    +1 for "I'll assume that the session scope is not an option, otherwise this question makes little sense." and following answer :) – niksvp May 05 '11 at 12:19
  • +1 for `` and `` and `JSF2.0` – jmj May 05 '11 at 12:24
  • @niksvp @jigar: the total vote count is 1. Who forgot to vote? :) – BalusC May 05 '11 at 12:27
  • btw system doesn't notify `@niksvp @jigar` to me on this – jmj May 05 '11 at 12:34
  • @jigar @niksvp and on this one? – BalusC May 05 '11 at 12:39
  • Now it does probably you forgot space between `jigar` and `:` – jmj May 05 '11 at 12:40
  • Oddly enough, RichFaces' version needs **only the name** of the bean, as seen in the sources on the [LiveDemo page for keepAlive](http://livedemo.exadel.com/richfaces-demo/richfaces/keepAlive.jsf?c=keepAlive), instead of a "legal JSF EL expression which resolves to a managed mean instance", as the [User's Guide](http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html/a4j_keepAlive.html) states. – Usagi Miyamoto Jan 22 '17 at 16:02
  • @UsagiMiyamoto Both are indeed allowed, but the EL expression one is more self-documenting. – BalusC Jan 22 '17 at 16:07
  • @BalusC When i tried it a few days ago **RichFaces 3.3.3.final** throw an exception about "the expression must evaluate to a string", and only was working when i replaced it with plain bean name. – Usagi Miyamoto Jan 22 '17 at 16:11
0

Not really, unless you store the Bean somewhere e.g. a Map in application scope, to retrieve it later.

Why not just make it Session scoped? This is what Session scope is there for, so multiple Requests during the same Session can hit the same state.

planetjones
  • 12,469
  • 5
  • 50
  • 51