0

这是我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);}
4

1 回答 1

0

只需将输入直接绑定到模型,而不是将模型展平和/或复制到支持 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 验证注释。此外,通过这种方式,您最终可以得到更简单的代码,而没有不必要的重复。

于 2013-09-11T12:37:47.607 回答