2

I've a JSF page that contains the following code:

...
<f:event type="preRenderView" listener="#{page1.PreRenderViewEvent}"/> 
...

Now I need to register the listener (Page1.PreRenderViewEvent method) NOT in the page but within the Page1 class constructor ... Something like:

...
UIViewRoot root = FacesContext.getCurrentInstance().getViewRoot();
root.getListenersForEventClass(javax.faces.event.PreRenderViewEvent.class).add ....
...

How I can complete this code ?
Thanks.

NCister
  • 235
  • 3
  • 9

1 Answers1

5

Use UIViewRoot#subscribeToViewEvent().

context.getViewRoot().subscribeToViewEvent(PreRenderViewEvent.class, new MySystemEventListener);

Note that this would be too late if the bean is constructed during render response phase as would happen during GET requests. You'd better just do the very job inside the constructor of the request scoped bean itself (or, cleaner, in a @PostConstruct).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thank you BalusC. For my job, I need a complete ViewRoot tree ... so Constructor and @PostConstruct are premature phases. Now, I've created a Class that implements SystemEventsListener ... but processEvent method isn't called .... – NCister Feb 26 '13 at 14:50
  • That's correct. But you explicitly stated "within the class constructor". So I was merely warning that this would not work if it's invoked during render response (and thus you're possibly looking for the solution in the wrong direction; for example, you don't need the event listener at all but you just need perform the very job which the listener is doing inside the (post)constructor itself). – BalusC Feb 26 '13 at 14:51
  • The whole component tree is definitely available in the constructor of a bean which is constructed during render response of a GET request. Have you checked it? Apparently not :) – BalusC Feb 26 '13 at 14:54
  • As said, again, it's too late if the bean is constructed during render response. In such case, you do not need the whole listener at all. Just do the very job directly in the (post)constructor. On the other hand, trying to access the component tree inside a backing bean is in turn an indication that you're possibly still overcomplicating things. If you elaborate the concrete functional requirement for which you possibly incorrectly thought that this all is the right solution, then we may be able to propose the real right solution. – BalusC Feb 26 '13 at 14:55
  • OK, now works ;-) ... In the listener implentation, the "isListenerForSource" method must return "True". – NCister Feb 26 '13 at 15:02
  • In the future, read the javadocs if you have no idea how to implement them. I assumed you already know how to read the javadocs. – BalusC Feb 26 '13 at 15:03