Scopes and @PostConstruct

1k views Asked by At

I'm using JSF 2, PrimeFacces 3.4 and CDI. I've 2 pages: page1.xhtml and page2.xhtml. Each page has its own managed bean: Page1Bean and Page2Bean.

page1.xhtml has a <p:remoteCommand> whose actionListener displays page2.xhtml.

page2.xhtml contains 3 components under <ui:include> and one submit button. Each of those 3 components are bound to different managed beans Component1Bean, Component2Bean and Component3Bean. The submit button shows page1.xhtml.

Those three ComponentXBeans have a @PostConstruct method with some initialization code. I tried the following scoped on those beans:

  • @SessionScoped: everything works fine for single submit operation. When I repeat it, then those beans are not reinitialized by @PostConstruct because those are session scoped.
  • @ViewScoped: the @PostConstruct gets called multiple times.
  • @ConversationScoped: same behavior as @ViewScoped.

Why is the @PostConstruct called multiple times in view and conversation scope? How can I let them to be called only once per submit operation?

1

There are 1 answers

0
Thomas W On

Running your initialization code under 'preRender' every time, is probably not correct. Since initialization will wipe out the data you want.

Separate your preRender from your initialization. You can either hook them separately, or have a flag to only call initialize() once.

Avoid Session-scoped beans if possible; session-scoping is the mark of badly-designed web applications and (in it's simplest forms) a very bad way to implement inter-page flow. Pass URL or POST parameters between web pages to implement flow.

If necessary, the inter-page parameters can be unique handles to objects stored in the HttpSession. But don't just dump stuff into the Session without it either being genuinely global to the application (such as "loggedInUser") or referenced by a uniquely-allocated handle.