gpt4 book ai didi

java - JSF 自定义 validator : h:message is not being rendered

转载 作者:行者123 更新时间:2023-11-30 06:35:20 25 4
gpt4 key购买 nike

我有以下 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-Log 中我可以看到

profileform:password: Old password is wrong!

我看不出有任何错误,特别是因为如果密码太长或太短,都会显示有关 f:validateLength 的消息。如果我这样做

context.addMessage(null, msg);

代替

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

消息显示在 h:messages 组件中。有人有想法吗?提前致谢

最佳答案

您什么也看不到,因为您构建了带有摘要详细信息的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));

它会如您所愿地工作。

关于java - JSF 自定义 validator : h:message is not being rendered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6168542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com