java - 如何在我的登录页面(JSF 2.0)实现多字段验证

标签 java jsf jakarta-ee jsf-2 java-ee-6

我需要对登录页面进行多字段验证(许多字段在同一方法中一次验证)。我不知道如何正确实现它。我正在按照我在以下位置找到的示例进行操作:http://balusc.blogspot.com/2007/12/validator-for-multiple-fields.html

我对 JSF 部分有点困惑。有人能帮我一把吗,我错过了什么?

页面:

<h:form>
    <p:panel>
        <h:outputText value="*Em@il:" />
        <h:inputText id="email" value="#{securityController.email}"
            required="true" />
        <br />
        <h:outputText value="*Password: " />
        <h:inputSecret id="password" value="#{securityController.password}"
            required="true">
            <f:validator validatorId="loginValidator" />
        </h:inputSecret>
        <br />
        <span style="color: red;"><h:message for="password"
                showDetail="true" /></span>
        <br />
        <h:commandButton value="Login" action="#{securityController.logIn()}" />
    </p:panel>
</h:form>

这是具有验证方法的托管 bean:

@ManagedBean
@RequestScoped
public class SecurityController implements Validator {

    @EJB
    private IAuthentificationEJB authentificationEJB;
    private String email;
    private String password;
    private String notificationValue;

    public String logIn() {
        if (authentificationEJB.saveUserState(email, password)) {
            notificationValue = "Dobro dosli";
            return "main.xhtml";
        } else {
            return "";
        }
    }

    public void validate(FacesContext context, UIComponent validate,
            Object value) {
        String emailInput = (String) value;
        String emailPatternText = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)"
            + "*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern emailPattern = null;
        Matcher emailMatcher = null;
        emailPattern = Pattern.compile(emailPatternText);
        emailMatcher = emailPattern.matcher(emailInput);
        String inputFromField = (String) value;
        String alphanumericPattern = "^[a-zA-Z0-9]+$";
        Pattern passwordPattern = null;
        Matcher passwordMatcher = null;
        passwordPattern = Pattern.compile(alphanumericPattern);
        passwordMatcher = passwordPattern.matcher(inputFromField);
        if (!emailMatcher.matches() && !passwordMatcher.matches()) {
            if (authentificationEJB.checkCredentials(email, password) == false) {
                FacesMessage msg = new FacesMessage(
                    "Pogresan email ili lozinka");
                throw new ValidatorException(msg);
            }
        }
    }

    public String getEmail() {
        return email;
    }

    public String getPassword() {
        return password;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNotificationValue() {
        return notificationValue;
    }

    public void setNotificationValue(String notificationValue) {
        this.notificationValue = notificationValue;
    }
}

与数据库交互以检查凭据的 EJB:

@Stateful(name = "ejbs/AuthentificationEJB")
public class AuthentificationEJB implements IAuthentificationEJB {

    @PersistenceContext
    private EntityManager em;

    // Login
    public boolean saveUserState(String email, String password) {
        // 1-Send query to database to see if that user exist
        Query query = em
            .createQuery("SELECT r FROM Role r WHERE r.email=:emailparam "
                + "AND r.password=:passwordparam");
        query.setParameter("emailparam", email);
        query.setParameter("passwordparam", password);
        // 2-If the query returns the user(Role) object, store it somewhere in
        // the session
        Role role = (Role) query.getSingleResult();
        if (role != null && role.getEmail().equals(email)
            && role.getPassword().equals(password)) {
            FacesContext.getCurrentInstance().getExternalContext()
                .getSessionMap().put("userRole", role);
            // 3-return true if the user state was saved
            System.out.println(role.getEmail() + role.getPassword());
            return true;
        }
        // 4-return false otherwise
        System.out.println(role.getEmail() + role.getPassword());
        return false;
    }

    // Logout
    public void releaseUserState() {
        // 1-Check if there is something saved in the session(or wherever the
        // state is saved)
        if (!FacesContext.getCurrentInstance().getExternalContext()
            .getSessionMap().isEmpty()) {
            FacesContext.getCurrentInstance().release();
        }
        // 2-If 1 then flush it
    }

    // Check if user is logged in
    public boolean checkAuthentificationStatus() {
        // 1-Check if there is something saved in the session(This means the
        // user is logged in)
        if ((FacesContext.getCurrentInstance().getExternalContext()
            .getSessionMap().get("userRole") != null)) {
            // 2-If there is not a user already loged, then return false
            return true;
        }
        return false;
    }

    @Override
    public boolean checkCredentials(String email, String password) {
        Query checkEmailExists = em
            .createQuery("SELECT COUNT(r.email) FROM Role r WHERE "
                + "r.email=:emailparam AND r.password=:passwordparam");
        checkEmailExists.setParameter("emailparam", email);
        checkEmailExists.setParameter("passwordparam", password);
        long matchCounter = 0;
        matchCounter = (Long) checkEmailExists.getSingleResult();
        if (matchCounter > 0) {
            return true;
        }
        return false;
    }
}

更新

删除了登录 validator

修改后的托管bean:

@ManagedBean
@RequestScoped
public class SecurityController {

    @EJB
    private IAuthentificationEJB authentificationEJB;
    private String email;
    private String password;
    private String notificationValue;

    public String logIn() {
        if (authentificationEJB.saveUserState(email, password)) {
            notificationValue = "Dobro dosli";
            return "main.xhtml";
        } else {
            return "";
        }
    }

    public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException {
        UIInput emailComponent = (UIInput) component.getAttributes().get(
            "emailComponent");
        String email = "";
        String password = "";
        email = (String) emailComponent.getValue();
        password = (String) value;
        String emailInput = email;
        String emailPatternText = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)"
            + "*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern emailPattern = null;
        Matcher emailMatcher = null;
        emailPattern = Pattern.compile(emailPatternText);
        emailMatcher = emailPattern.matcher(emailInput);
        String passwordInput = password;
        String alphanumericPattern = "^[a-zA-Z0-9]+$";
        Pattern passwordPattern = null;
        Matcher passwordMatcher = null;
        passwordPattern = Pattern.compile(alphanumericPattern);
        passwordMatcher = passwordPattern.matcher(passwordInput);
        if (!emailMatcher.matches() && !passwordMatcher.matches()) {
            if (authentificationEJB.checkCredentials(emailInput, passwordInput) == false) {
                FacesMessage msg = new FacesMessage(
                    "Pogresan email ili lozinka");
                throw new ValidatorException(msg);
            }
        }
        if (emailInput == null || passwordInput == null) {
            FacesMessage msg = new FacesMessage("Zaboraviliste nesto");
            throw new ValidatorException(msg);
        }
        if (passwordInput.length() <= 0 || emailInput.length() <= 0) {
            FacesMessage msg = new FacesMessage("Zaboraviliste nesto");
            throw new ValidatorException(msg);
        }
    }
    // Get set methods
}

登录表单:

<h:form>
    <p:panel>
        <h:outputText value="*Em@il:" />
        <h:inputText id="email" value="#{securityController.email}"
            binding="#{emailComponent}" />
        <br />
        <h:outputText value="*Password: " />
        <h:inputSecret id="password" value="#{securityController.password}"
            validator="#{securityController.validate}">
            <f:attribute name="emailComponent" value="#{emailComponent}" />
        </h:inputSecret>
        <br />
        <span style="color: red;"><h:message for="password"
                showDetail="true" /></span>
        <br />
        <h:commandButton value="Login" action="#{securityController.logIn()}" />
    </p:panel>
</h:form>

修改了 EJB 中的 saveUserState() 方法:

// Login
public boolean saveUserState(String email, String password) {
    // 1-Send query to database to see if that user exist
    Query query = em
        .createQuery("SELECT r FROM Role r WHERE r.email=:emailparam "
            + "AND r.password=:passwordparam");
    query.setParameter("emailparam", email);
    query.setParameter("passwordparam", password);
    // 2-If the query returns the user(Role) object, store it somewhere in
    // the session
    try {
        Role role = (Role) query.getSingleResult();
        if (role != null && role.getEmail().equals(email)
            && role.getPassword().equals(password)) {
            FacesContext.getCurrentInstance().getExternalContext()
                .getSessionMap().put("userRole", role);
            // 3-return true if the user state was saved
            System.out.println(role.getEmail() + role.getPassword());
            return true;
        }
    } catch (Exception e) {
        // This fix the bug that does not display the message when wrong
        // password!
        FacesMessage msg = new FacesMessage("Pogresan email ili lozinka");
        throw new ValidatorException(msg);
    }
    // 4-return false otherwise
    return false;
}

最佳答案

您需要通过 binding 绑定(bind)第一个组件并将其作为您正在验证的组件的属性传递。您还需要使用 validator输入字段的属性而不是 <f:validator>当您想在托管 bean 中调用 validator 方法时。最后你应该摆脱 implements Validator在 bean 类上。

<h:outputText value="*Em@il:" />
<h:inputText id="email" binding="#{emailComponent}" value="#{securityController.email}" required="true"/>                   
<br/>
<h:outputText value="*Password: " />
<h:inputSecret id="password" value="#{securityController.password}" validator="#{securityController.validateEmailAndPassword}" required="true">
    <f:attribute name="emailComponent" value="#{emailComponent}" />
</h:inputSecret> 

public void validateEmailAndPassword(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    UIInput emailComponent = (UIInput) component.getAttributes().get("emailComponent");
    String email = (String) emailComponent.getValue();
    String password = (String) value;

    // ...
}

关于java - 如何在我的登录页面(JSF 2.0)实现多字段验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5650697/

相关文章:

javascript - Jscolor 在第一次回发新部署后停止工作,但在回发重新加载后继续工作

java - chalice 或玩!对于前 RoR 开发人员?

java - 为什么在这个基本的 Java 程序中会出现 InputMismatchException?

java - 动态壁纸关闭后还在运行

java - 使用比较器对 VO 的嵌套列表进行排序

java - 控制台类java

jsf - 在 URL 中使用 & 会导致 XML 错误 : The reference to entity "foo" must end with the ';' delimiter

jsf - Richfaces 日历最小和最大日期

java - 如何使用java上传文件而不改变其编码

java - 无法在服务器部署上启动 Quartz