簡體   English   中英

密碼錯誤時,登錄表單不顯示驗證消息

[英]Login form doesn't display validation message when password is wrong

我有一個由JSF頁面+托管bean + EJB組成的登錄機制,它可以正常工作,但是唯一的錯誤是當密碼輸入錯誤時我看不到錯誤消息。 有任何想法嗎?

當密碼輸入錯誤時,這是​​我在瀏覽器中看到的:

在此處輸入圖片說明

如果我沒有在EJB的陷阱處拋出ValidationException(請參閱下面的EJB代碼),但是當密碼輸入錯誤時,我根本看不到任何驗證消息,可以避免這種情況。

這是頁面上表單的代碼:

<h:form>
   <p:panel>                
                <h:outputText value="*Em@il:" />
                <h:inputText id="email" value="#{securityController.email}" binding="#{emailComponent}"/>                   
                <br/>
                <h:outputText value="*Lozinka: " />
                <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>

這是managedBean的代碼:

    @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("Pogresan email ili lozinka");
            throw new ValidatorException(msg);
        }
        if (passwordInput.length() <= 0 || emailInput.length() <= 0) {
            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
        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) {
                            FacesMessage msg = new FacesMessage("Pogresan email ili lozinka");
            throw new ValidatorException(msg); 
        }
        // 4-return false otherwise
        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;
    }
}

在EJB中,如果我將ValidationException扔到catch塊中,我認為我會犯錯,因為我認為在前端顯示錯誤消息應該是托管bean的任務。 我不明白為什么密碼不正確時,表單不顯示錯誤,因為字段為空(當電子郵件錯誤時,它正確顯示了驗證消息)。

更新資料

將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
    List<Object> tmpList = query.getResultList();
    if (tmpList.isEmpty() == false) {
        Role role = (Role) tmpList.get(0);
        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
    return false;
}

檢查憑證方法:

public boolean checkCredentials(String email, String password) {
    Query checkEmailExists = em
            .createQuery("SELECT COUNT(r) FROM Role r WHERE r.email=:emailparam AND r.password=:passwordparam");
    checkEmailExists.setParameter("emailparam", email);
    checkEmailExists.setParameter("passwordparam", password);
    int matchCounter = 0;
    matchCounter = checkEmailExists.getResultList().size();
    if (matchCounter == 1) {
        return true;
    }
    return false;
}

您不應將JSF ValidatorException扔在EJB方法內,而應扔在JSF validate()方法內。

我不確定導致此異常的EJB出了什么問題,可能getSingleResult()根本沒有返回單個結果(因此為零或許多)。 您需要通過使用getResultList()或修改您的數據模型來相應地更改/處理該用戶為何沒有單一角色的原因。 我認為您只需要getResultList()因為您顯然允許null結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM