【问题标题】:perform a simple check on the form fields (NotEmpty)对表单字段执行简单检查(NotEmpty)
【发布时间】:2013-09-11 09:51:44
【问题描述】:

这是我的方法SaveClient(),即使所有字段都为空,它也会创建一个新客户端!

public void SaveClient() {

    client = new Client();
    client.setNom(nom);
    client.setPrenom(prenom);
    client.setAdresse(adresse);
    client.setDomaine(domaine);
    client.setRaisonSociale(raisonSociale);
    client.setDateDAbonnement(dateDAbonnement);
    client.setDateFAbonnement(dateFAbonnement);
    client.setType(type);
    client.setEmail(email);
    client.setnFixe(nFixe);
    client.setnGsm(nGsm);
    client.setnFixe2(nFixe2);
    client.setnGsm2(nGsm2);
    client.setVille(ville);
    client.setPays(pays);

    Set<ConstraintViolation<Client>> violations = validator
            .validate(client);
    basicController.<Client> processValidation(violations);

    if (violations.size() == 0) {
        clientBean.creerClient(client);
        basicController.addMessage(" Client has been created successfully",
                FacesMessage.SEVERITY_INFO, null);}

【问题讨论】:

  • 如果所有字段为空,我想添加验证检查以不添加客户端!

标签: jsf-2 bean-validation


【解决方案1】:

只需将输入直接绑定到模型,而不是将模型展平和/或复制到支持 bean。

即做

@Named
public class Bean {

    private String firstname;
    private String lastname;
    private String address;
    // ...

    public void save() {
        Client client = new Client(firstname, lastname, address /* , ...*/);
        clientService.save(client);
    }

}

<h:inputText value="#{bean.firstname}" />
<h:inputText value="#{bean.lastname}" />
<h:inputText value="#{bean.address}" />
...

而是这样做

@Named
public class Bean {

    private Client client;

    @PostConstruct
    public void init() {
        client = new Client();
    }

    public void save() {
        clientService.save(client);
    }

}

<h:inputText value="#{bean.client.firstname}" />
<h:inputText value="#{bean.client.lastname}" />
<h:inputText value="#{bean.client.address}" />
...

如果你有一个

@Entity
public class Client {

    @NotNull
    private String firstname;

    @NotNull
    private String lastname;

    @NotNull
    private String address;

    // ...
}

这样,JSF 将自动考虑 Client 类中的任何 bean 验证注释。此外,通过这种方式,您可以得到更简单的代码,而不会出现不必要的重复。

【讨论】:

    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2016-10-09
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多