java - 如何使用确认密码验证密码然后重定向?

标签 java jsp jakarta-ee jsf-2

如何在 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/

相关文章:

java - 当我创建类的新实例时,为什么会出现 java.lang.NullPointerException?

Java - 对对象进行事务处理的方法

java - 使用 dateParam 进行 JSTL 查询

java - 保护 url 的最佳方式,以便只有定义的方才能相互交互

java - 如何使用Servlet验证JSP并保留输入数据?

java - 为什么 Java 被称为更高效(在资源消耗方面)但速度较慢,这在 Web 应用程序的上下文中有何优势?

jakarta-ee - 具有注释 javax.servlet.annotation.WebServlet 的类 x 需要是 javax.servlet.http.HttpServlet 的派生类

java - 盒子布局无法对齐

Java 小程序无法在 Azure 中运行

java - 如何将 WorkManager 与 GlassFish 3 结合使用?