2

我想在运行时初始化我的文本字段。例如,我有这样的primefaces inputtext:

<p:inputText value="#{myBean.value}" id="inputText" />

还有一个豆类:

@PostConstruct
public void onPageLoad() {
    ....
    ....
    inputText.setMaxlength(15);
    inputText.setStyle(".....");
}

jsf 2.0可以做到这一点吗?

4

2 回答 2

3

You could do so by binding the component to the bean:

<p:inputText binding="#{bean.input}" ... />

with

private InputText input; // +getter+setter

@PostConstruct
public void init() {
    input = new InputText();
    input.setMaxlength(15);
    input.setStyle("background: pink;");
}

// ...

This is however not the recommended approach. You should rather bind the individual attributes to a bean property instead.

<p:inputText ... maxlength="#{bean.maxlength}" style="#{bean.style}" />

with

private Integer maxlength;
private String style; 

@PostConstruct
public void init() {
    maxlength = 15;
    style = "background: pink;";
}

// ...

Even more, if your app is well designed, then you should already have such a bean object for this (why/how else would you like to be able to specify it during runtime?). Make it a property of the managed bean instead so that you can do something like:

<p:inputText ... maxlength="#{bean.attributes.maxlength}" style="#{bean.attributes.style}" />
于 2012-06-04T20:35:15.730 回答
0

为此,您可以使用以下代码从 jsf 框架中获取组件对象

UIComponent componentObj = FacesContext.getCurrentInstance().getViewRoot().findComponent(id)

然后您可以在标签组件类型中键入 cast 组件对象,就像您使用 inputText 一样

HtmlInputText inputTextObj = (HtmlInputText) componentObj;

和 HtmlInputText 类具有标签中所有可用属性的所有 getter 设置器,因此您可以设置诸如

inputTextObj.setMaxlength(15);
inputTextObj.setStyle(....);
inputTextObj.setDisabled();
inputTextObj.setReadonly();
于 2012-06-05T08:10:37.727 回答