Группы валидаторов Hibernate с помощью Spring MVC - PullRequest
0 голосов
/ 06 января 2012

Пожалуйста, вы можете мне помочь?

У меня проблема с валидатором Hibernate / Spring 3 MVC для проверки с группами.

В моем spring-config.xml :

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

Мой bean-компонент для проверки :

package fr.test.front.form;

import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.NotBlank;

import fr.test.front.constraints.ConstraintsProfessionnel;
import fr.test.front.constraints.FieldMatch;

@FieldMatch.List({
    @FieldMatch(first = "password", second = "passwordConfirm", message = "Les mots de passe ne correspondent pas")
})
public class InfoPersoForm {

    // Commons attributs
    @NotBlank
    private String clientType;

    @Pattern(regexp = "(([\\w\\-\\.]+)([\\w]+))@((([\\w\\-]+\\.)+)([a-zA-Z]{2,4}))")
    @NotBlank
    private String email;

    @Pattern(regexp = "[a-zA-Z0-9]*")
    @NotBlank
    private String password;

    @NotBlank
    private String passwordConfirm;

    @NotBlank
    private String civilite;

    @NotBlank
    private String nom;

    @NotBlank
    private String prenom;

    @NotBlank
    private String codePostal;

    @NotBlank
    private String offresCommerciales;

    @NotBlank
    private String offresCommercialesPartenaire;

    // No Constraint
    private String nomNaissance;
    private String jourNaissance;
    private String moisNaissance;
    private String anneeNaissance;


    // Attributs for professionnal
    @NotBlank(groups = ConstraintsProfessionnel.class)
    private String raisonSociale;

    @NotBlank(groups = ConstraintsProfessionnel.class)
    private String secteurActivite;

    @NotBlank(groups = ConstraintsProfessionnel.class)
    private String entiteeJuridique;

    // getters and setters ...
}

В моем Spring Controller я приведу javax.validation.Валидатор в org.springframework.validation.Validator, чтобы связать результирующие ограничения.Я хочу видеть ошибки проверки в моем представлении результатов:

@InitBinder
public void initBinder(WebDataBinder binder) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    binder.setValidator((org.springframework.validation.Validator)validator);
}

Здесь мое inscriptionWeb действие:

@RequestMapping(value="inscriptionWeb", method = RequestMethod.POST)
public String createCompteInternetService(@ModelAttribute("infoPersoForm") @Valid InfoPersoForm infoPersoForm, BindingResult result, SessionStatus status, Model model) {

    Set<ConstraintViolation<InfoPersoForm>> constraintViolations = validator.validate(infoPersoForm);

    //printing the results
    for (ConstraintViolation<InfoPersoForm> constraintViolation : constraintViolations) {
        System.out.println(constraintViolation.getPropertyPath() + " -> " +
                constraintViolation.getMessage() + "   " + constraintViolation.getMessageTemplate());
    }

    System.out.println("");
    System.out.println("----- Using Group -----");
    System.out.println("");

    constraintViolations = validator.validate(infoPersoForm, ConstraintsProfessionnel.class);

    //printing the results
    for (ConstraintViolation<InfoPersoForm> constraintViolation : constraintViolations) {
        System.out.println(constraintViolation.getPropertyPath() + " -> " + constraintViolation.getMessage());
    }


    if(infoPersoForm.getClientType() != null && infoPersoForm.getClientType().equals(DonneesReferencesInvariantes.CLIENT_TYPE_PROFESSIONNEL_VALUE))
        validator.validate(infoPersoForm, ConstraintsProfessionnel.class);
    else
        validator.validate(infoPersoForm);

    if (result.hasErrors()) {
        // return error view
    }
    else {
        // return success view
    }
}

Первый вопрос , У меня есть только один constraintsProfessionnel (raisonSociale) в моих результатах групп проверки (см. Мою консоль результатов после), Почему?

Где находятся другие ограниченияProfessionnel (secteurActivite и entiteeJuridique)?Их нет в моих ограничениях: ошибка:

    19:29:42,128 INFO  [STDOUT] codePostal -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:42,128 INFO  [STDOUT] offresCommerciales -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:42,129 INFO  [STDOUT] email -> doit suivre "(([\w\-\.]+)([\w]+))@((([\w\-]+\.)+)([a-zA-Z]{2,4}))"   {javax.validation.constraints.Pattern.message}
19:29:42,129 INFO  [STDOUT] email -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:42,129 INFO  [STDOUT] passwordConfirm -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:42,129 INFO  [STDOUT] prenom -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:42,129 INFO  [STDOUT] offresCommercialesPartenaire -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:42,129 INFO  [STDOUT] civilite -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:42,129 INFO  [STDOUT] nom -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:42,129 INFO  [STDOUT] password -> ne peut pas être vide   {org.hibernate.validator.constraints.NotBlank.message}
19:29:54,803 INFO  [STDOUT] ----- Using Group -----
19:29:54,812 INFO  [STDOUT] codePostal -> ne peut pas être vide
19:29:54,812 INFO  [STDOUT] offresCommerciales -> ne peut pas être vide
19:29:54,812 INFO  [STDOUT] email -> doit suivre "(([\w\-\.]+)([\w]+))@((([\w\-]+\.)+
([a-zA-Z]{2,4}))"
19:29:54,812 INFO  [STDOUT] email -> ne peut pas être vide
19:29:54,812 INFO  [STDOUT] passwordConfirm -> ne peut pas être vide
19:29:54,812 INFO  [STDOUT] prenom -> ne peut pas être vide
19:29:54,812 INFO  [STDOUT] offresCommercialesPartenaire -> ne peut pas être vide
19:29:54,813 INFO  [STDOUT] raisonSociale -> ne peut pas être vide
19:29:54,813 INFO  [STDOUT] civilite -> ne peut pas être vide
19:29:54,813 INFO  [STDOUT] nom -> ne peut pas être vide
19:29:54,813 INFO  [STDOUT] password -> ne peut pas être vide

Второй вопрос , у моего объекта результата есть только ограничения по умолчанию, а не ConstraintsProfessionnel (raisonSociale, secteurActivite и entiteeJuridique), вы можете объяснитьпочему они не находятся в моем объекте результата?

1 Ответ

0 голосов
/ 07 января 2012

Как мне известно, Spring проверяет только группу по умолчанию для параметров метода контроллера.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...