JSF 生命周期流程验证阶段

JSF lifecycle process validation phase

我编写了一个带有两个验证器的简单 JSF 应用程序来理解 JSF 流程验证阶段。这是验证器:

@FacesValidator("second")
public class AnotherValidator implements Validator{
    public void validate(FacesContext arg0, UIComponent arg1, Object arg2)
            throws ValidatorException {
        System.out.println("Validation phase, the second");
        FacesContext.getCurrentInstance().renderResponse();
        throw new ValidatorException(new FacesMessage("The second"));
    }
}

@FacesValidator("first")
public class ProducerValidator implements Validator{
    public void validate(FacesContext arg0, UIComponent arg1, Object arg2)
            throws ValidatorException {
        System.out.println("Validation phase, the first");
        FacesContext.getCurrentInstance().renderResponse();
        throw new ValidatorException(new FacesMessage("The first"));
    }
}

我认为如果我们从 validate 方法调用 renderResponse 方法,JSF 实现应该跳到渲染响应阶段。但实际上我有以下控制台输出:

Validation phase, the first
Validation phase, the second

尽管从第一个验证器调用了 renderResponse,第二个验证器仍然被调用...为什么? Facelets 标记:

<h:inputText value="#{helloBean.p}" converter="conv">
    <f:validator validatorId="first"/>
    <f:validator validatorId="second" />
</h:inputText> 

这是指定的行为。来自 FacesContext#renderResponse() javadoc:

Signal the JavaServer faces implementation that, as soon as the current phase of the request processing lifecycle has been completed, control should be passed to the Render Response phase, bypassing any phases that have not been executed yet.

因此,它不会像您预期的那样突然中止当前阶段。它将完成当前阶段,然后前进到渲染响应阶段。

只是,当您从验证器内部抛出 ValidatorException 时,默认情况下它已经这样做了。所以,两者都没有必要。