扩展UIComponentBase时如何保存状态 [英] How to save state when extending UIComponentBase

查看:181
本文介绍了扩展UIComponentBase时如何保存状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个复合组件,它将包装数据表以实现非常简单的分页。我需要在ajax请求之间保存状态(当前页码)。

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.

我尝试在我的FacesComponent中创建字段,但我发现它们在JSF生命周期中被清除了:

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?

推荐答案

使用 StateHelper 。它可以通过 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);
}

请注意,我返回的默认值为在getter中0 。您可能希望将 int 更改为 Integer 并删除默认值,以便 null 将被退回。

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.

无关到具体问题,你可以为了更简单,还可以扩展 UINamingContainer 而不是实现 NamingContainer 。这样你可以省略被覆盖的 getFamily()方法,因为它已经由 UINamingContainer 正确实现。

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.

这篇关于扩展UIComponentBase时如何保存状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆