JSF自定义验证器:h:message没有被呈现



我有以下FacesValidator:

@RequestScoped
@FacesValidator("passwordValidator")
public class PasswordValidator implements Validator {
    @PersistenceUnit(unitName = "TradeCenterPU")
    private EntityManagerFactory emf;
    @Override
    public void validate(final FacesContext context, final UIComponent comp, final Object values) throws ValidatorException {
        String password = (String)values;
        System.out.println("passwordValidator():" + password);
        EntityManager em = emf.createEntityManager();
        Query q = em.createNamedQuery("user.findByUsername");
        q.setParameter("username", context.getExternalContext().getRemoteUser());
        User user = (User)q.getSingleResult();
        String pwhash = DigestUtils.md5Hex(password + user.getSalt());
        System.out.println("User: " + user.getUsername() + ", PwHash: " + pwhash + ", Password: " + user.getPassword());
        if (!pwhash.equals(user.getPassword())) {
            System.out.println(comp.getClientId(context) + ": Old password is wrong!");
            FacesMessage msg = new FacesMessage(
                    FacesMessage.SEVERITY_ERROR,
                    "The old password was not entered correctly.",
                    ""
            );
            context.addMessage(comp.getClientId(context), msg);
            throw new ValidatorException(msg);
        }
    }
}

Wich的使用方式如下:

<h:form id="profileform" action="#{userController.updatePassword}">
    <h:messages errorClass="error_message" globalOnly="true"/>
    ...
    <h:outputLabel for="password" value="Old password:" />
    <h:inputSecret id="password" name="password" label="Old password">
        <f:validateLength minimum="8" maximum="15" />
        <f:validator validatorId="passwordValidator"/>
    </h:inputSecret>
    <h:message for="password" errorClass="error_message"/>
    ...
</h:form>

现在的问题是,Validator生成的消息永远不会显示。我知道它会被生成,因为在Glassfish日志中我可以看到

profileform:password: Old password is wrong!

我看不到任何错误,尤其是因为如果密码太长或太短,就会显示f:validateLength的消息。如果我做

context.addMessage(null, msg);

而不是

context.addMessage(comp.getClientId(context), msg);

消息被显示在CCD_ 2组件中。有人有主意吗?提前感谢

您什么也看不到,因为您已经用摘要细节构建了FacesMessage。当详细信息不是null时,将显示它。由于您已经用一个空字符串设置了它,所以您"看到"了一条空消息。您基本上需要将detail设置为null才能显示摘要。

但这并不是你应该在验证错误上设置消息的方式。您应该抛出ValidatorException,JSF将根据组件的客户端ID将ValidatorException构造的消息添加到上下文本身。

所以,你需要更换

FacesMessage msg = new FacesMessage(
        FacesMessage.SEVERITY_ERROR,
        "The old password was not entered correctly.",
        ""
);
context.addMessage(comp.getClientId(context), msg);
throw new ValidatorException(msg);

通过

String msg = "The old password was not entered correctly.";
throw new ValidatorException(new FacesMessage(msg));

它会如你所期望的那样工作。

最新更新