JSF validator with custom method

旧时模样 提交于 2019-12-13 01:30:01

问题


This is fragment of my Bean:

public class WaiterBean extends Connector
{
    private String PIN;
    private String name = null;

    public void setPIN(String PIN)
    {
        this.PIN = PIN;
    }
    public String getPIN() 
    {
        return PIN;
    }
    public String getName() 
    {
        return name;
    }
    public String isPINCorrect(String PIN) 
    {
        try 
        {
            resultSet = statement.executeQuery(
                "SELECT name FROM dbo.waiters WHERE PIN=" + PIN);
            while(resultSet.next())
            {
                name = resultSet.getString("name"); 
            }
        } 
        catch (SQLException se) 
        {
            System.out.println(se.getMessage() + "**"
                + se.getSQLState() + "**" + se.getErrorCode());
        }
        if(name == null)
            return "invalid";
        else
            return "valid";
    }
}

This is validator bean:

public class PINValidator implements Validator
{

    @Override
    public void validate(FacesContext fc, UIComponent uic, Object o) throws ValidatorException 
    {
        String PIN = o.toString();
        if(PIN.length() < 4)
        {
            FacesMessage msg = new FacesMessage("PIN too short");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
    }
}

And this is how I use it:

<h:form>
    <h:panelGrid columns="2">
        ENTER PIN
        <h:inputText id="PIN" maxlength="4" size="4" value="#{waiterBean.PIN}">
            <f:validator validatorId="com.jsf.PINValidator" />
        </h:inputText>
    </h:panelGrid>
    <h:message for="PIN"/> 
    <br />
    <h:commandButton value="SEND" action="#{waiterBean.isPINCorrect(waiterBean.PIN)}" />
    <br />
</h:form>

Everything works fine, but I think it's good practice to include the isPINCorrect method in the validator class (am I wrong?). I can implement the method in the validator, but then I have a problem how to setName for the WaiterBean and it's needed for the application.

How should I resolve the problem? Or another question, should I even try to resolve it?


回答1:


You can access a session scoped managed bean from a validator like this:

facesContext.getExternalContext().getSessionMap().get("waiterBean");

But I don't think this is the best practice in your case because a validator should not modify data, should only check for the validity of the input. The main reason for this at the validation phase the model is not updated yet, and modifying your bean in the validator can cause some side-effects.

Take a look at JSF Lifecycle



来源:https://stackoverflow.com/questions/16490740/jsf-validator-with-custom-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!