How to save state when extending UIComponentBase

 ̄綄美尐妖づ 提交于 2019-12-17 06:14:31

问题


I'm creating a composite component that will wrap a datatable to implement very simple paging. I need to save state (the current page number) between ajax requests.

I tried creating fields in my FacesComponent, but I discovered they are wiped out during the JSF lifecycle:

@FacesComponent(value = "bfTableComponent")
public class BFTableComponent extends UIComponentBase implements NamingContainer {

    private int currentPageNumber;
    ...

I can't seems to find a concise guide to doing this anywhere! How would one save state between requests when creating a composite component?


回答1:


Use StateHelper. It's available by UIComponent#getStateHelper().

private enum PropertyKeys {
    currentPageNumber;
}

public void setCurrentPageNumber(int currentPageNumber) {
    getStateHelper().put(PropertyKeys.currentPageNumber, currentPageNumber);
}

public int getCurrentPageNumber() {
    return (int) getStateHelper().eval(PropertyKeys.currentPageNumber, 0);
}

Note that I'm returning a default value of 0 in the getter. You might want to change int to Integer and remove the default value so that null will be returned.


Unrelated to the concrete problem, you can for more simplicity also just extend UINamingContainer instead of implementing NamingContainer. This way you can omit the overridden getFamily() method as it's already implemented rightly by UINamingContainer.



来源:https://stackoverflow.com/questions/9405278/how-to-save-state-when-extending-uicomponentbase

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