在验证错误发生后,如何使用PrimeFaces AJAX填充文本字段?

Eri*_*nez 45 validation ajax jsf primefaces

我在视图中有一个表单,它执行自动完成和gmap本地化的ajax部分处理.我的支持bean实例化一个实体对象"Address",并且该对象引用了表单的输入:

@ManagedBean(name="mybean")
@SessionScoped
public class Mybean implements Serializable {
    private Address address;
    private String fullAddress;
    private String center = "0,0";
    ....

    public mybean() {
        address = new Address();
    }
    ...
   public void handleAddressChange() {
      String c = "";
      c = (address.getAddressLine1() != null) { c += address.getAddressLine1(); }
      c = (address.getAddressLine2() != null) { c += ", " + address.getAddressLine2(); }
      c = (address.getCity() != null) { c += ", " + address.getCity(); }
      c = (address.getState() != null) { c += ", " + address.getState(); }
      fullAddress = c;
      addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, "Full Address", fullAddress));
      try {
            geocodeAddress(fullAddress);
        } catch (MalformedURLException ex) {
            Logger.getLogger(Mybean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Mybean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Mybean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Mybean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(Mybean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (XPathExpressionException ex) {
            Logger.getLogger(Mybean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void geocodeAddress(String address)
            throws MalformedURLException, UnsupportedEncodingException,
            IOException, ParserConfigurationException, SAXException,
            XPathExpressionException {

        // prepare a URL to the geocoder
        address = Normalizer.normalize(address, Normalizer.Form.NFD);
        address = address.replaceAll("[^\\p{ASCII}]", "");

        URL url = new URL(GEOCODER_REQUEST_PREFIX_FOR_XML + "?address="
                + URLEncoder.encode(address, "UTF-8") + "&sensor=false");

        // prepare an HTTP connection to the geocoder
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        Document geocoderResultDocument = null;

        try {
            // open the connection and get results as InputSource.
            conn.connect();
            InputSource geocoderResultInputSource = new InputSource(conn.getInputStream());

            // read result and parse into XML Document
            geocoderResultDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(geocoderResultInputSource);
        } finally {
            conn.disconnect();
        }

        // prepare XPath
        XPath xpath = XPathFactory.newInstance().newXPath();

        // extract the result
        NodeList resultNodeList = null;

        // c) extract the coordinates of the first result
        resultNodeList = (NodeList) xpath.evaluate(
                "/GeocodeResponse/result[1]/geometry/location/*",
                geocoderResultDocument, XPathConstants.NODESET);
        String lat = "";
        String lng = "";
        for (int i = 0; i < resultNodeList.getLength(); ++i) {
            Node node = resultNodeList.item(i);
            if ("lat".equals(node.getNodeName())) {
                lat = node.getTextContent();
            }
            if ("lng".equals(node.getNodeName())) {
                lng = node.getTextContent();
            }
        }
        center = lat + "," + lng;
    }
Run Code Online (Sandbox Code Playgroud)

在我提交整个表单之前,自动完成和映射ajax请求工作正常.如果验证失败,除了在视图中无法更新的字段fullAddress之外,ajax仍然正常工作,即使在ajax请求之后在辅助bean上正确设置了它的值.

<h:outputLabel for="address1" value="#{label.addressLine1}"/>
<p:inputText required="true" id="address1" 
          value="#{mybean.address.addressLine1}">
  <p:ajax update="latLng,fullAddress" 
          listener="#{mybean.handleAddressChange}" 
          process="@this"/>
</p:inputText>
<p:message for="address1"/>

<h:outputLabel for="address2" value="#{label.addressLine2}"/>
<p:inputText id="address2" 
          value="#{mybean.address.addressLine2}" 
          label="#{label.addressLine2}">
  <f:validateBean disabled="#{true}" />
  <p:ajax update="latLng,fullAddress" 
          listener="#{mybean.handleAddressChange}" 
          process="address1,@this"/>
</p:inputText>
<p:message for="address2"/>

<h:outputLabel for="city" value="#{label.city}"/>
<p:inputText required="true" 
          id="city" value="#{mybean.address.city}" 
          label="#{label.city}">
  <p:ajax update="latLng,fullAddress" 
          listener="#{mybean.handleAddressChange}" 
          process="address1,address2,@this"/>
</p:inputText>
<p:message for="city"/>

<h:outputLabel for="state" value="#{label.state}"/>
<p:autoComplete id="state" value="#{mybean.address.state}" 
          completeMethod="#{mybean.completeState}" 
          selectListener="#{mybean.handleStateSelect}"
          onSelectUpdate="latLng,fullAddress,growl" 
          required="true">
  <p:ajax process="address1,address2,city,@this"/>
</p:autoComplete>
<p:message for="state"/> 

<h:outputLabel for="fullAddress" value="#{label.fullAddress}"/>
<p:inputText id="fullAddress" value="#{mybean.fullAddress}" 
          style="width: 300px;"
          label="#{label.fullAddress}"/>
<p:commandButton value="#{label.locate}" process="@this,fullAddress"
          update="growl,latLng" 
          actionListener="#{mybean.findOnMap}" 
          id="findOnMap"/>

<p:gmap id="latLng" center="#{mybean.center}" zoom="18" 
          type="ROADMAP" 
          style="width:600px;height:400px;margin-bottom:10px;" 
          model="#{mybean.mapModel}" 
          onPointClick="handlePointClick(event);" 
          pointSelectListener="#{mybean.onPointSelect}" 
          onPointSelectUpdate="growl" 
          draggable="true" 
          markerDragListener="#{mybean.onMarkerDrag}" 
          onMarkerDragUpdate="growl" widgetVar="map"/>
<p:commandButton id="register" value="#{label.register}" 
          action="#{mybean.register}" ajax="false"/>
Run Code Online (Sandbox Code Playgroud)

如果我刷新页面,验证错误消息将消失,并且ajax按预期完成fullAddress字段.

在验证期间还会发生另一种奇怪的行为:我已禁用表单字段的bean验证,如代码所示.这项工作没问题,直到找到其他验证错误,然后,如果我重新提交表单,JSF会为此字段进行bean验证!

我想我在验证状态期间遗漏了一些内容,但我无法弄清楚它有什么问题.有谁知道如何调试JSF生命周期?有任何想法吗?

Bal*_*usC 82

通过考虑以下事实可以理解问题的原因:

  • 当JSF验证成功用于在验证阶段的特定输入组件,然后提交的值被设置为null与所述验证值被设定为输入组件的局部值.

  • 在验证阶段,当特定输入组件的JSF验证失败时,提交的值将保留在输入组件中.

  • 如果在验证阶段后至少有一个输入组件无效,则JSF将不会更新任何输入组件的模型值.JSF将直接进入呈现响应阶段.

  • 当JSF呈现输入组件时,它将首先测试提交的值是否未null显示,然后显示它,否则如果本地值不null显示然后显示它,否则它将显示模型值.

  • 只要您与相同的JSF视图交互,就可以处理相同的组件状态.

因此,当特定表单提交的验证失败并且您碰巧需要通过不同的ajax操作或甚至不同的ajax形式更新输入字段的值时(例如,根据下拉选择或某些结果填充字段)模态对话框表单等),然后你基本上需要重置目标输入组件,以使JSF显示在调用操作期间编辑的模型值.否则,JSF仍将显示其在验证失败期间的本地值,并使它们处于无效状态.

其中的方式你的具体情况是手动收集将被更新/被重新呈现输入组件的所有ID PartialViewContext#getRenderIds(),然后手动重置其状态和提交的值EditableValueHolder#resetValue().

FacesContext facesContext = FacesContext.getCurrentInstance();
PartialViewContext partialViewContext = facesContext.getPartialViewContext();
Collection<String> renderIds = partialViewContext.getRenderIds();

for (String renderId : renderIds) {
    UIComponent component = viewRoot.findComponent(renderId);
    EditableValueHolder input = (EditableValueHolder) component;
    input.resetValue();
}
Run Code Online (Sandbox Code Playgroud)

您可以在handleAddressChange()侦听器方法内部执行此操作,也可以在可重用的ActionListener实现中执行此操作<f:actionListener>,该实现将作为调用handleAddressChange()侦听器方法的输入组件附加.


回到具体问题,我想这是JSF2规范中的一个疏忽.当JSF规范强制要求时,JSF开发人员会更有意义:

  • 当JSF需要通过ajax请求更新/重新呈现输入组件,并且该输入组件未包含在ajax请求的进程/执行中时,JSF应该重置输入组件的值.

这已被报告为JSF问题1060和一个完整的,可重复使用的解决方案已在已实施OmniFaces库作为ResetInputAjaxActionListener(源代码在这里,展示演示在这里).

更新1:从版本3.4开始,PrimeFaces基于这个想法也引入了一个完整且可重复使用的解决方案<p:resetInput>.

更新2:从版本4.0开始,<p:ajax>获得了一个新的布尔属性resetValues,该属性也可以解决此类问题,而无需额外的标记.

更新3: JSF 2.2引入<f:ajax resetValues>,遵循相同的想法<p:ajax resetValues>.该解决方案现在是标准JSF API的一部分.

  • 如果这是个严重错误,那么我会徘徊,当简单而琐碎的任务需要那么多的知识和代码行时。这项技术出了点问题,我不知道它仍然是程序员的工具,还是管理员执行任务的工具,没人应该关心。 (2认同)