无法验证在jsf 2.0中使用ajax呈现的输入文本字段

时间:2013-02-06 01:36:24

标签: ajax jsf-2 rendering requiredfieldvalidator

<h:form>
 <h:selectManyMenu id="carsList"
                   value="#{bean.carList}"
                   style="width:400px; height:100px" label="List">
                    <f:selectItems  value="#{bean.cars}" var="i"
                                    itemLabel="#{i.code}" itemValue="#{i.Name}" />
                    <f:selectItem  itemLabel="Other" itemValue="other"/>
                    <f:ajax event="change" execute="@this" render="othermodel"/>
        </h:selectManyMenu>
                    <br></br>
                    <h:panelGroup id="othermodel">
                            <h:outputText  value="Others:" style="margin-top:10px;color:red;font-weight:bold;"
                            rendered="#{bean.carList.contains('other')}" />
                            <h:inputText size="50" id="otherinput" required="true"
                            rendered="#{bean.carList.contains('other')}"/>
                            <h:message for="otherinput"></h:message>
                    </h:panelGroup>
                       <h:commandButton value="Next" action="#{bean.submitForm}"/>
    </h:form>

我的bean是requestScoped,当我的carList的值为other时,我能够显示panelGrid但是当用户没有在输入中输入任何值时使用AJAX呈现的字段,即使我指定了required=true,但它没有得到验证。并且后端代码中输入文本框的值为null。

如何对使用AJAX呈现的输入字段进行验证,以及为什么我的值为null?我正在使用JSF 2.0

2 个答案:

答案 0 :(得分:1)

在表单提交请求期间重新评估rendered属性。您的bean是请求作用域,因此在每个请求(也是ajax请求)上重新创建,并将所有属性设置为default。因此,carList属性也将被清空,rendered属性将在更新模型值阶段填充false之前评估carList。因此,对于JSF,<h:inputText>永远不会被渲染,因此不会被处理。

将bean放在视图范围内。只要您通过(ajax)回发与相同的视图进行交互,它就会存在。对于具有大量条件渲染的基于动态ajax的表单,它是正确的范围。

另见:

答案 1 :(得分:0)

我用@ViewScope尝试了这个。当我将Spring managed service作为瞬态时,我在反序列化后获得null引用。所以,我尝试了以下方法来获取Spring Service

    @ManagedBean(name="bean")
    @ViewScoped
    public class Bean implements Serializable {


    @ManagedProperty(value="#{appService}")
    private transient AppService appService;

      // Getting AppService Object which is singleton in the application during deserialization 
     private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
              stream.defaultReadObject();
              FacesContext context = FacesContext.getCurrentInstance();
              appService = (AppService)context.getApplication()
                    .evaluateExpressionGet(context, "#{appService}", AppService.class);
                  stream.close();  // not sure i have to do this
           }
    }

这对我没有任何问题。