Run a method in Managedbean when initializing the Page

Asked

Viewed 5,005 times

0

Greetings Pessoal.

I wonder if there is any formal way to execute a method in Managedbean when invoking/initializing a page?

I have already done this, usually by putting EL directly on the page, before any other JSF element, and I feel (suspect) that is not the right way to do.

Ex: Suppose there is a people registration page, and whenever the page is loaded, I need to print a text on the server side.

What I’ve been doing is something like:

...
<html ...>

    <h:head>
        ...
    </h:head>

    <h:body>
        <h:form>
            #{beanTeste.imprimirNome()}
            ...
        </h:form>
    </h:body>
</html>

Grateful from now on.

2 answers

4


Personal greetings.

The best solution I found (without wanting to dispense with the help already presented here) is the use of the type of event preRenderView for the tag f:event.

Allows the execution of method during the start of the presentation response phase (JSF page), ie before the page is presented it gives the possibility to perform a task.

Ex:

<html ... xmlns:f="http://java.sun.com/jsf/core"> 
    <f:event listener="#{beanTeste.imprimirNome()}" type="preRenderView" /> 
    <h:body>
        ... 
    </h:body> 
</html>

More details:

https://stackoverflow.com/questions/9844526/when-to-use-prerenderview-versus-postconstruct http://www.tutorialspoint.com/jsf/jsf_event_handling.htm

Example:

http://www.mkyong.com/jsf2/jsf-2-prerenderviewevent-example/

API:

https://javaserverfaces.java.net/docs/2.1/vdldocs/facelets/f/event.html

3

There is a note that fits exactly in your case.

Use the annotation @PostConstruct to define a method that is executed as soon as the ManagedBean is built (according to the life cycle of your Bean), that is, when the first EL which references the Bean is found.

For example:

@ViewScoped
// ou
@RequestScoped
@Named
public class MeuBean {

    @PostConstruct
    public void inicializar() {
        // Sua logica de inicializacao
    }
}

There is also the @PreDestroy, similar to the @PostConstruct, is called when a Bean will be destroyed. The call varies in relation to the scope of your Bean (the call depends on the life cycle). If you use a Bean scoped View there is a bug in most implementations that do not call this life cycle method correctly.

That question predestroy-em-viewscoped addresses this behavior.


As his Bean is of session, the @PostConstruct is only called once, regardless of how many times it is accessed on your page.

We know the application server manages the lifecycle of Beans. Soon it will create and destroy your session bean. It will create on the first reference to it and will destroy when the session is invalidated, storing it in the session in the meantime.

I have two suggestions to solve the problem, which would be:

  1. Replace the session bean with a @ViewScoped or @RequestScoped, and "caching" the result of processing it does or uses in the session. Using @PostConstruct to print what you need on the console. This is valid if your Bean session is no longer required after such replacement.

    Because in the matter of memory loss, it is even more advantageous than the Bean session by storing only the result and not the entire bean. But in terms of organization and OO, the session bean will do better because there will be a "context" around the data, all logic regarding this data will be centralized in one place. In case, the choice will depend a lot on how this your organization.

  2. Create a Bean @ViewScoped or @RequestScoped and inject your session bean to use it in @PostConstruct. In terms of code it would be something like this:

    @RequestScoped
    @Named
    public class MeuBeanDeImpressao {
    
        // Injeto o Bean de sessão
        @ManagedProperty("#{beanTeste}")
        // ou
        @Inject
        BeanTeste beanTeste;
    
        @PostConstruct
        public void inicializa() {
            beanTeste.imprimirNome();
        }
    }
    

    This case is only advantageous if you still need the session bean, but can use a @RequestScoped or @ViewScoped on your page (having use for other things, otherwise it may generate unnecessary memory). @RequestScope if it works better because there is no bug in the life cycle, it will be destroyed after use.

  • Thank you for the @Wakim reply. I only had one question: If it is a MB of the Session scope, this method will be executed every time the page is invoked/initialized?

  • No, it only invoked the first time it is referenced (created).

  • Well then the mistake was mine, I was not so explicit. I would like to always execute the method every time the page was invoked, I will edit the question.

  • Yeah, that solution would only fit if your bean was ViewScoped.

  • Exact! In the same thanks for the tip, we always gave to increase the knowledge of a possibility.

  • @Coldhack, I’ll put some alternatives to your case soon, just I come home.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.