Perform business logic after getters are called

耗尽温柔 提交于 2019-12-02 16:58:46

问题


I would like to write my business logic after the getters and setters are called (twice), because I use their object values inside the business logic. However Construct, Post construct, actionevents,.. are called before the getters.

So how can I use the values of the getters if I don't want to write business logic inside them?


回答1:


I want to navigate to the site and get data from a database displayed into outputText.

Do the job in (post)constructor of the bean.

@ManagedBean
@RequestScoped
public class Bean {

    private String data;

    @EJB
    private SomeService service;

    @PostConstruct
    public void init() {
        data = service.load();
    }

    // Getter.
}

with

<h:outputText value="#{bean.data}" />

When I change a (primefaces)selectOneMenu value the bean gets the selectOneMenu's value and performs a query in the database for this value, and writes the query result inside the outputText.

Do the job in the ajax listener method of the bean which is attached to input component's change event.

@ManagedBean
@ViewScoped
public class Bean {

    private String selectedItem;
    private String result;

    @EJB
    private SomeService service;

    public void changeSelectedItem(AjaxBehaviorEvent event) {
        result = service.find(selectedItem);
    }

    // Getters+setter.
}

with

<p:selectOneMenu value="#{bean.selectedItem}">
    <f:selectItems ... />
    <p:ajax listener="#{bean.changeSelectedItem}" update="result" />
</p:selectOneMenu>
<h:outputText id="result" value="#{bean.result}" />

Doing it after the getters are called would be too late. JSF would at that point already be finished with rendering the HTML output. You can't change the HTML output afterwards.




回答2:


You are making a basic mistake in your thinking.

There is no such phase as "The Getters". Getters are just a convention to read a property of a bean.

Those properties can be read individually throughout the entire request. Some may be consulted as early as during "create/restore view", while others may be consulted during "render response".

There is no such thing as that JSF in one particular phase does a sweep through your code and for the fun of it calls every getter it finds.

The solution for you is to let this thinking go. I know it might be hard to let go of something you think is true, but inhale, clear you mind, say goodbye to your current understanding of how things work, and just re-learn from scratch.

You'll then find the answer yourself in no-time. Good luck!




回答3:


Did not understand your question fully, but obvious way is to put logic in getters and setters.



来源:https://stackoverflow.com/questions/15568838/perform-business-logic-after-getters-are-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!