Given: JSF2 Form with some input fields, including password field.
Main Goal: If the password field is left empty (resulting in password.isEmpty()==true
or password==null
), the validation and password binding should be skipped!
No-Go: Separate DTO (i know it would be more clean, but i am not allowed to decide this)
view.xhtml:
<h:form id="someForm">
<h:outputLabel value="Password " />
<h:inputSecret id="password" value="#{myBackingBean.entity.password}" immediate="true" redisplay="false" required="false">
<f:validateBean disabled="true"/>
<f:validator validatorId="myPasswordValidator"/>
</h:inputSecret>
<p:message for="password" />
<p:commandButton value="Save" update="someForm">
<f:actionListener binding="#{myBackingBean.updateEntityAction()}" />
</p:commandButton>
</h:form>
MyPasswordValidator.java:
@FacesValidator(value = "myPasswordValidator")
public class MyPasswordValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
String password = (String) value;
if (password == null || password.isEmpty()) {
UIInput inputComponent = ((UIInput) component);
inputComponent.setValid(true);
inputComponent.setRequired(false);
}
return;
}
}
MyBackingBean.java:
@ManagedBean(name = "myBackingBean")
@ViewScoped
public class MyBackingBean extends GenericBackingBean<....> {
public ActionListener updateEntityAction(){
return new ActionListener() {
@Override
public void processAction(ActionEvent event)
throws AbortProcessingException {
// .... hybernate stuff
}
};
}
}
Entity.java:
class Entity{
@NotNull
private String password;
// ...
public void setPassword(String password) {
// do nothing if null
if(password == null || password.isEmpty()){
log.warn("Password not changed for some reason ....");
return;
}
// set and crypt password ...
}
This actually works, but only for the first submit, each submit after the first results in a error message (no exception ... probably it gets eaten somewhere ... ?). What is interesting, is that the message says "kann nicht null sein'" (german), and i have actually no clue who or what is producing this message.
What i conclude, is that after the first submit the default bean validation is activated again.
Any Idea?