Check if username already exists in the register f

2019-06-06 05:50发布

问题:

I have the follwing register form:

 <h:form id="newCustomerForm"  >
                <fieldset>
                    <legend>Register Form</legend>
                    <table border="0" >
                        <tbody > 
                            <tr type="text">

                                <td>
                                    <p:outputLabel  value="Account Login :" for="pseudo"/>    
                                </td>
                                <p:spacer height="5px" />
                                <td>
                                    <p:inputText id="pseudo" value="#{customerMB.login}" title="Pseudo" required="true" requiredMessage="The Pseudo field is required."/>
                                    <p:watermark for="pseudo" value="Login" />  
                                    <p:message for="pseudo"/>
                                </td>

                            </tr>
                            <p:spacer height="5px" />  
                            <tr type="password">

                                <td>
                                    <p:outputLabel  value="Password :" for="pwd1"/>
                                </td>
                                <p:spacer height="5px" />
                                <td>
                                    <p:password id="pwd1" value="#{customerMB.password}" feedback="true" match="pwd2" label="Password 1" required="true" requiredMessage="The Password field is required."/>  
                                    <p:watermark for="pwd1" value="Password" />  
                                    <p:message for="pwd1"/>
                                </td>

                            </tr>
                            <p:spacer height="5px" /> 
                            <tr type="password">
                                <td>
                                    <p:outputLabel  value="Confirm password :" for="pwd2"/>
                                </td>
                                <p:spacer height="5px" />
                                <td>
                                    <p:password id="pwd2" value="#{customerMB.password}" feedback="true" label="Password 2" required="true" requiredMessage="The confirm password field is required."/>  
                                    <p:watermark for="pwd2" value="Confirm Password" />  
                                    <p:message for="pwd2"/>
                                </td>
                            </tr>
                            <p:spacer height="5px" />         
                            <tr type="text">
                                <td>
                                    <p:outputLabel  value="Email address :" for="email"/>
                                </td>
                                <p:spacer height="5px" />
                                <td>
                                    <p:inputText id="email" value="#{customerMB.email}"  title="Email" required="true" validatorMessage="Insert a valid email" requiredMessage="The Email field is required.">
                                        <f:validateRegex pattern="([^.@]+)(\.[^.@]+)*@([^.@]+\.)+([^.@]+)" />
                                    </p:inputText>
                                    <p:watermark for="email" value="Email" /> 
                                    <p:message for="email"/>
                                </td>
                            </tr>
                            <p:spacer height="5px" /> 

                            <tr type="text">  
                                <td>
                                    <p:outputLabel  value="First Name :" for="name"/>
                                </td>
                                <p:spacer height="5px" />
                                <td>
                                    <p:inputText id="name" value="#{customerMB.name}" title="Name" required="true" requiredMessage="The Name field is required." styleClass="error"/>
                                    <p:watermark for="name" value="First Name" />  
                                    <p:message for="name"/>
                                </td>
                            </tr>
                            <p:spacer height="5px" />
                            <tr type="text">
                                <td>
                                    <p:outputLabel  value="Last Name :" for="familyName"/>
                                </td>
                                <p:spacer height="5px" />
                                <td>
                                    <p:inputText id="familyName" value="#{customerMB.familyName}" title="FamilyName" required="true" requiredMessage="The FamilyName field is required."/>                                                         
                                    <p:watermark for="familyName" value="Last Name" />  
                                    <p:message for="familyName"/>
                                </td>
                            </tr>
                            <p:spacer height="5px" />
                            <tr type="text">
                                <td>
                                    <p:outputLabel  value="Organization :" for="organisation"/>
                                </td>
                                <p:spacer height="5px" />
                                <td>
                                    <p:inputText id="organisation" value="#{customerMB.organisation}" title="Organisation" required="true" requiredMessage="The Organisation field is required."/>
                                    <p:watermark for="organisation" value="Organisation" />   
                                    <p:message for="organisation"/>
                                </td>
                            </tr>
                            <p:spacer height="5px" />   
                            <tr type="text">
                                <td>
                                    <p:outputLabel  value="Country :" for="country"/>
                                </td>
                                <p:spacer height="5px" />
                                <td>
                                    <p:selectOneMenu id="country" style="width: 292px" value="#{customerMB.address.country}" required="true" requiredMessage="The Status field is required." >
                                        <f:selectItem itemLabel="Select Country"  itemValue="" />
                                        <f:selectItems value="#{customerMB.allCountries}" />
                                    </p:selectOneMenu>
                                    <p:watermark for="country" value="Country" /> 
                                    <p:message for="country"/>
                                </td>
                            </tr>
                            <p:spacer height="5px" />                         
                            <p:spacer height="5px" />
                        </tbody>
                    </table>
                    <div type="submit" align="right" style="margin-top: 5px">

                        <p:commandButton style="margin-right: 20px" value="Save" ajax="false" icon="ui-icon-circle-check" styleClass="ui-priority-primary" action="#{customerMB.addCustomer()}" />                                                    
                        <p:commandButton  value="Cancel" icon="ui-icon-arrowrefresh-1-n" onclick="location.href = 'login.jsp';"  process="@this"  >  
                            <p:resetInput target="customerPannel" />  
                        </p:commandButton> 

                    </div>  
                </fieldset>    

            </h:form>

The method that persists a user account in my ViewScoped Bean is:

public String addCustomer() throws IOException {
        logger.log(Level.SEVERE, "*****add customer***** ");
        creation = new Date();
        right = Right.SimpleUser;
        Customer customerRegister = customerLocal.addUser(name, familyName, address, email, right, creation, organisation);
        accountBusinessLocal.addAccount(login, password, customerRegister);
        return "login.jsp";
    }

And this is my account ManagedBean

public class AccountBusiness implements AccountBusinessLocal {

    @Inject
    private AccountManagerLocal accountManagerLocal;

    @Override
    public Account addAccount(String login, String password, Customer customer) {
        Account account;
        account = accountManagerLocal.createAccount(login, password);
        account.setCustomer(customer);
        accountManagerLocal.persistAccount(account);
        return account;
    }

    @Override
    public boolean authentificateUser(String username, String password) {
        Account account = accountManagerLocal.findByLogin(username);
        if (account != null) {
            if (password.equalsIgnoreCase(account.getPassword())) {
                return true;
            }
        }
        return false;
    }
}

I want to add a control in the account login input text that checks if the username is already used by another user or not. If yes the user should get a message and re-enter an available username. How can i do this??

回答1:

One way to do it is by submitting your input on blur and checking if it's duplicated. In case it's duplicated you will need to register a message specific for that component, in this case, I will bind the input to be able to access the component's id from my bean.

Here is a sample (and tested) code that contains the relevant elements you will need:

View

<h:form id="mainForm">
    <h:panelGrid id="grid" columns="3" cellpadding="4">  
        <p:outputLabel for="pseudo" value="Login" />
        <p:inputText id="pseudo" value="#{viewMBean.login}" binding="#{viewMBean.loginInput}" title="Pseudo" required="true" requiredMessage="The Pseudo field is required."
                     placeholder="Login">
            <p:ajax event="blur" listener="#{viewMBean.checkDuplicateLogin}" update="pseudoMsg" />
        </p:inputText>
        <p:message id="pseudoMsg" for="pseudo" />
    </h:panelGrid>
    <p:commandButton value="Register" />
</h:form>

Bean

import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

@ManagedBean
@ViewScoped
public class ViewMBean implements Serializable {

    private UIComponent loginInput;

    private String login;

    public void checkDuplicateLogin() {
        //replace with your own fancy code
        if (login.equals("admin")) {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(loginInput.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "Duplicated Login", null));
        }
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public UIComponent getLoginInput() {
        return loginInput;
    }

    public void setLoginInput(UIComponent loginInput) {
        this.loginInput = loginInput;
    }

}


回答2:

Make changes to addCustomer() method as below . I've added comments for you to get an idea.

public String addCustomer() throws IOException {
        //you don't need password to check though
        boolean isExist = accountBusinessLocal.authentificateUser(login,password);
        if(isExist){
        //return empty
        FacesContext context = FacesContext.getCurrentInstance(
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Duplicated Login", null));
        return "";          
        }

        logger.log(Level.SEVERE, "*****add customer***** ");
        creation = new Date();
        right = Right.SimpleUser;
        Customer customerRegister = customerLocal.addUser(name, familyName, address, email, right, creation, organisation);
        accountBusinessLocal.addAccount(login, password, customerRegister);
        return "login.jsp";
    }

Update: In order to show message ,add p:message tag inside the form.

<p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" />