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>
现在的问题是,验证器生成的消息从不显示。我知道它是生成的,因为在Glassfish日志中,我可以看到
profileform:password: Old password is wrong!
我看不到任何错误,特别是因为如果密码太长或太短都会显示ѭ3的消息。 如果我做
context.addMessage(null,msg);
代替
context.addMessage(comp.getClientId(context),msg);
消息显示在“ 6”组件中。 有人知道吗?提前致谢     

解决方法

        您什么也看不到,因为您已用摘要和详细信息构造了ѭ7。当细节不是
null
时,它将显示出来。由于您使用空字符串设置了它,因此您“看到”了一条空消息。基本上,您需要将详细信息设置为
null
才能显示摘要。 但这并不完全是您应该为验证错误设置消息的方式。您只需要抛出“ 10”,JSF就会根据组件的客户端ID将“ 10”构造的消息添加到上下文本身。 因此,您需要更换
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));
它将按您的预期工作。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...