禁用启用 jsf f:convertDateTime

Disable enable jsf f:convertDateTime

我有两个按钮,其中一个我需要 <f:convertDateTime> 才能工作,但另一个我需要在单击按钮时禁用 <f:convertDateTime>

我尝试了属性 rendereddisabled,但没有用,这是我的错误,因为根据 API 文档,它不可用。

此外,是否有一种方法可以覆盖 class javax.faces.converter.DateTimeConverter,以便在触发 f:convertDateTime 时调用我的 class?

我猜你有一些基于点击按钮的文本显示(如果我错了请纠正我)。所以它应该是这样的:

<h:commandButton value="Convert" action="#{bean.doBtnConvert}" />

<h:commandButton value="Don't convert" action="#{bean.doBtnDontConvert}" />

<h:panelGroup id="pgText">
    <h:outputText value="#{bean.someDateTime}" rendered="#{bean.convert}">
        <f:convertDateTime pattern="dd.MM.yyyy HH:mm:ss" />
    </h:outputText>

    <h:outputText value="#{bean.someDateTime}" rendered="#{not bean.convert}"> />
</h:panelGroup>

在 bean 中,您有以下字段和方法:

private Date someDate;
private boolean convert;

public String doBtnConvert(){
    setConvert(true);
    String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
    return viewId + "?faces-redirect=true";
}

public String doBtnDontConvert(){
    setConvert(false);
    String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
    return viewId + "?faces-redirect=true";
}

// getter and setter for 'someDate' and 'convert' fields

I tried the attributes rendered and disabled, but it didn't work, which was my mistake as it is not available as per the API docs.

的确,不支持此行为。但是,对于可能的解决方案,你基本上已经自己给出了答案:

Also, is there a way to override the class javax.faces.converter.DateTimeConverter such that whenever f:convertDateTime is triggered my class will be called?

这是可能的,也将解决您最初的问题。只需将其注册为 <converter> in faces-config.xml on exactly the same <converter-id> as <f:convertDateTime>.

<converter>
    <converter-id>javax.faces.DateTime</converter-id>
    <converter-class>com.example.YourDateTimeConverter</converter-class>
</converter>

您可以在其中进行额外的条件检查,例如检查某个按钮是否被按下,或者某个请求参数是否存在。如果您想继续默认的 <f:convertDateTime> 工作,只要您的转换器 extends 来自 DateTimeConverter.

,只需委派给 super

例如在 getAsObject():

public class YourDateTimeConverter extends DateTimeConverter {

    @Override
    public void getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        // ...

        if (yourCondition) {
            // Do your preferred way of conversion here.
            // ...
            return yourConvertedDateTime;
        } else {
            // Do nothing. Just let default f:convertDateTime do its job.
            return super.getAsObject(context, component, submittedValue);
        }
    }

    // ...
}