3

I have to call a init method on my bean as first action on the page load, I have tried to simply call #{bean.init} at the very beginning of my page, but I have seen that the <c:if> tests are performed before the init(). I have something like

#{bean.init}
<c:if test="#{bean.conditionsCheck}">...</c:if>

and the conditionsCheck() method is called before the init(), how can I fix it and call init() as really first thing?

Tiny
  • 27,221
  • 105
  • 339
  • 599
Cattani Simone
  • 1,168
  • 4
  • 12
  • 30

3 Answers3

6

You can use the @PostConstruct annotation to automatically invoke your init method:

@PostConstruct
public void init() {
  // do something
}

This method is automatically invoked after construction of the bean.

Your solution looks more like a f:event with type="preRenderView" but this can't be used because the c:if tags are evaluated during view build time, while the f:event (respectively your solution) runs right before the view is rendered during render response phase. Have a look at this question and this question to get details.

Update: As you commented you are using a @SessionScoped bean where @PostConstruct is only called once per session and not on every page load. In this case another solution would be to call your init method as first statement in your conditionsCheck method (nearly the same as your suggestion with fake c:if boolean init). You could also use a custom PhaseListener but I guess that would be somewhat overdosed for this problem.

See also:

Community
  • 1
  • 1
unwichtich
  • 13,712
  • 4
  • 53
  • 66
  • As described in the question he is using a simple EL call to invoke the method. Anyway, shouldn't the @PostConstruct fix the problem? – unwichtich Jan 05 '14 at 16:38
  • Indeed, but `preRenderView` won't solve the problem. See also http://stackoverflow.com/q/3342984/ – BalusC Jan 05 '14 at 16:45
  • I don't know if @PostConstruct will solve the problem, but it will introduce another problem, for SessionScoped it runs only after the initialization of the bean, not every time that I reload a page – Cattani Simone Jan 05 '14 at 18:06
  • I will solve the problem using a "fake" c:if testing a "Boolean init()" – Cattani Simone Jan 05 '14 at 18:09
0

This works if you add a JSF Control like CommandButton, and in its value you write it as:

value="#{sessionScopedBean.method()}"

This method will be called whenever this page loads.

Makoto
  • 104,088
  • 27
  • 192
  • 230
-1

for anyone searching ...

We can use preRender of scriptCollector tag, if the used JSF implementation supports it, something like:

<scriptCollector id="scriptCollector1" preRender="#{bean.method}">
...
</scriptCollector>
Moro
  • 2,088
  • 6
  • 25
  • 34