首先单击commandButton不会重定向到另一个页面

gue*_*est 2 ajax jsf jsf-2.2

  1. 当我输入有效值(仅数字)到inputText并单击commandButton然后我被重定向到response.xhtml.

  2. 当我输入无效值时,单击页面背景,然后触发更改事件,显示消息.现在当我输入有效值并单击commandButton时,消息会隐藏,但我没有被重定向.当我第二次点击时,我被重定向.

的index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form>
            <h:panelGrid>
                <h:inputText id="value" value="#{bean.value}">
                    <f:validateRegex pattern="\d+"/>
                    <f:ajax event="change" execute="@this" render="@this valueMessage"/>
                </h:inputText>
                <h:message id="valueMessage" for="value"/>
            </h:panelGrid>

            <h:commandButton value="OK" action="response"/>
        </h:form>
    </h:body>
</html>
Run Code Online (Sandbox Code Playgroud)

response.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        Value is <h:outputText value="#{bean.value}"/>
    </h:body>
</html>
Run Code Online (Sandbox Code Playgroud)

Bean.java

package app;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class Bean {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 5

您的具体问题是由隐藏消息引起的,这反过来导致命令按钮在其自己的单击事件结束之前向上移动,因此当释放鼠标按钮并且即将触发表单提交时,不再位于鼠标指针下方.如果将消息组件移动到命令按钮组件下面,如下所示,

<h:commandButton value="OK" action="response"/>
<h:message id="valueMessage" for="value"/>
Run Code Online (Sandbox Code Playgroud)

...然后,当消息隐藏时,命令按钮将保留在UI中的相同位置,因此将成功接收其单击事件并触发表单提交.

这只是一个UI设计问题,而不是技术问题.您需要尝试确保按钮在其单击事件完成之前不会移开.

一种方法是使表格宽2列,以便消息显示在输入字段旁边而不是在其下方,因此不占用更多的水平空间:

<h:panelGrid columns="2">
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用<f:ajax delay>属性延迟ajax请求(仅在JSF 2.2之后可用).我测试了几个值,100~200ms似乎可以接受平均点击的时间跨度(从鼠标按钮按下直到实际释放鼠标按钮的时间).这样,当单击提交按钮时,实际上不会触发ajax请求,从而避免按钮的移位(以及"不必要的"验证).

<f:ajax render="@this valueMessage" delay="150" />
Run Code Online (Sandbox Code Playgroud)

(注意event="change"并且execute="@this"它们是默认值,它们已经在上面的例子中省略了;技术上render="@this"也很奇怪,但我只是保留它,因为你实际上想要在一些转换步骤后重新显示更改的值)