简体   繁体   English

用户输入错误密码后,验证信息未以登录形式显示

[英]Validation message not being displayed in login form when the user enters wrong password

I am trying to understand why my login form does not display the validation message that says "wrong email or password" when the password is entered wrong. 我试图理解为什么当密码输入错误时,我的登录表单为什么不显示“错误的电子邮件或密码”的验证消息。 In all the other cases it works correctly(Just case 4 doesnt work): 在所有其他情况下,它都可以正常工作(只是情况4不起作用):

Case 1 works with no problem(No input given): 情况1没问题(没有输入):

在此处输入图片说明

Case 2 works with no problem(Only input given for email): 情况2正常工作(仅输入电子邮件): 在此处输入图片说明

Case 3 works with no problem(Only input given for password): 情况3没问题(仅输入密码): 在此处输入图片说明

Case 4 doesn't work (Both inputs given wrong) 情况4不起作用 (两个输入均输入错误)

在此处输入图片说明

It is the case 4 that doesn't work correctly here is the source code: 情况4不能正常工作,这里是源代码:

The form at the JSF page: JSF页面上的表单:

<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>   

The managed bean that gets the values from the input fields 从输入字段获取值的托管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("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;
    }
}

The EJB that accesses the DB and checks the credentials: 访问数据库并检查凭据的EJB:

package ejbs;

import java.util.List;
import javax.ejb.Stateful;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ejbinterfaces.IAuthentificationEJB;
import entities.Role;

@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
        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;
    }

    // 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()) {
            // 2-If 1 then flush it
            FacesContext.getCurrentInstance().release();
        }       
    }

    // 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) 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;
    }
}
if (!emailMatcher.matches() && !passwordMatcher.matches()) {
    if (authentificationEJB.checkCredentials(emailInput, passwordInput) == false) {
        FacesMessage msg = new FacesMessage(
                "Pogresan email ili lozinka");
        throw new ValidatorException(msg);
    }
}

Thus, when the email doesn't match AND the password doesn't match AND the credentials doesn't match, then the error message will be displayed. 因此,当电子邮件不匹配且密码不匹配且凭据不匹配时,将显示错误消息。

This is not exactly what you want. 这不是您想要的。 In case 4 the email do match. 在第4种情况下,电子邮件确实匹配。 You want this: 你要这个:

if (!emailMatcher.matches() || !passwordMatcher.matches() || !authentificationEJB.checkCredentials(emailInput, passwordInput)) {
    FacesMessage msg = new FacesMessage("Pogresan email ili lozinka");
    throw new ValidatorException(msg);
}

This will show the error when the email doesn't match OR the password doesn't match OR the credentials doesn't match. 当电子邮件不匹配或密码不匹配或凭据不匹配时,将显示错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 密码错误时,登录表单不显示验证消息 - Login form doesn't display validation message when password is wrong 密钥克隆-重置密码时未显示未找到用户的消息信息 - Keycloack - User not found message information not displayed when reset password Java-用户在布尔中输入字符串时的验证 - Java - Validation when user enters string into boolean 如何以登录形式获取失败的用户或密码消息 - how to get fail user or password message in login form 在Spring Form验证中未显示给定的错误消息 - Given error message is not displayed in Spring Form validation 我想在用户输入错误密码后发出警报(验证来自数据库),我需要从Servlet生成警报,该怎么做? - I want throw an alert after the user enters wrong password (the validation is from DB), I need to generate alert from my Servlet, how to do that? 当用户输入字母字符时,对数字字段进行播放验证 - Play's validation on numeric fields when user enters in alpha characters 当用户输入非双精度值的内容时,如何打印错误消息? - How to print error message when user enters anything that is not a double? 尝试解析日期时显示错误的日期 - Wrong date being displayed when trying to parse a date 当用户输入错误的字符或无效的输入数据时,如何显示“打印”错误? - How to display a “print” error when the user enters wrong character or invalid input data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM