如何在 login.jsp
中使用确认密码验证密码,只有当密码相等时,才重定向到显示 Welcome #{beans.用户名
.
最佳答案
只需执行一个 Validator
通常的方式。肯定不应该像其他人建议/暗示的那样在操作方法中进行验证。如果验证失败,则默认情况下将不会调用操作方法,并且将重新显示同一页面并显示验证错误。您可以将密码字段作为 <f:attribute>
传递确认密码字段,以便 validator 可以获取其值以进行测试。
这是 View 的启动示例:
<h:inputSecret id="password" binding="#{passwordComponent}" value="#{bean.password}" required="true" />
<h:message for="password" />
<h:inputSecret id="confirm" required="#{not empty password.value}">
<f:validator validatorId="confirmPasswordValidator" />
<f:attribute name="passwordComponent" value="#{passwordComponent}" />
</h:inputText>
<h:message for="confirm" />
和 validator :
@FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
UIInput passwordComponent = (UIInput) component.getAttributes().get("passwordComponent");
String password = (String) passwordComponent.getValue();
String confirmPassword = (String) value;
if (confirmPassword != null && !confirmPassword.equals(password)) {
throw new ValidatorException(new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Confirm password is not the same as password", null));
}
}
}
该消息将出现在 <h:message for="confirm">
中.
请注意,您只需要将密码作为辅助 bean 中的属性,而不是确认密码。
private String password;
// Getter+setter.
在操作方法中,您可以按照通常的方式返回导航案例结果:
public String login() {
User user = userService.find(username, password);
if (user != null) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", user);
return "success?faces-redirect=true";
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_WARN, "Unknown login, please try again.", null));
return null;
}
}
自 JSF 2.0 以来,faces-config.xml
中不再需要冗长的导航案例。不再像其他答案所暗示的那样。
无关具体问题,你为什么还坚持使用遗留的JSP View 技术?这一直是deprecated从 JSF 2.0 开始支持 Facelets。请考虑migrating JSP 到 Facelets。然后您将能够使用新的 JSF 2.0 <f:ajax>
。令人敬畏和强大的 Facelets 模板功能。
关于java - 如何使用确认密码验证密码然后重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12703787/