2012-02-12 3 views
2

Я всегда использовал @Valid и BindingResult для проверки полей формы. Теперь, используя Ajax, на основе статьи this, нельзя использовать BindingResult вместо или дополнительно к HttpServletResponse, потому что это приведет к неправильному запросу (код ошибки HTTP 400).Spring Form Ajax Request + Hibernate Validation

Как подтвердить мои поля формы сейчас?

@RequestMapping(value = "/save.html", params = "json", method = RequestMethod.POST) 
    public @ResponseBody Map<String, ? extends Object> saveJSON(@RequestBody Location location, /* BindingResult result, */ HttpServletResponse response) 
    { 
    return Collections.singletonMap("foo", "foobar"); 
    } 

Это был старый путь без AJAX:

@RequestMapping(value = "/save.html", method = RequestMethod.POST) 
    public String save(@ModelAttribute("location") @Valid Location location, BindingResult result, Map<String, Object> map) 
    { 
    Location l; 
    if ((l = service.findByTitle(location.getTitle())) != null) 
    { 
     if (location.getId() != l.getId()) 
     { 
     result.addError(new FieldError("location", "title", messageSource.getMessage("Unique.location.title", null, null))); 
     } 
    } 

    if (result.hasErrors()) 
    { 
     return "locationform"; 
    } 

    service.save(location); 
    return "redirect:/locations/index.html"; 
    } 

EDIT

Пробовал, но нет errors члена в результате который содержит true при выходе из формы незаполненного (это должно привести к сообщение @NotEmpty Constraint)

@RequestMapping(value = "/save.html", params = "json", method = RequestMethod.POST) 
    public @ResponseBody Map<String, ? extends Object> saveJSON(@RequestBody Location location, HttpServletResponse response, Map<String, Object> map) 
    { 
    BindingResult result = new BeanPropertyBindingResult(location, ""); 
    if (result.hasErrors()) map.put("errors", true); 
    map.put("foo", "foobar"); 
    return map; 
    } 
+0

Какая версия Весна вы используете 3,0 или 3,1? – Ralph

+0

@Ralph я использую весну 3.1 – dtrunk

ответ

1

Кажется, вы используете валидатор спящего режима. Если это так попробуйте этот

в вашем контроллер:

//other imports 
import javax.validation.Validator; 
@Controller() 
class MyController{ 

    @autowire() 
    @qualifier("myValidator") 
    private Validator validator; 
    public Validator getValidator() { 
     return mValidator; 
    } 

    public void setValidator(Validator validator) { 
     this.mValidator = validator; 
    } 

    @RequestMapping(value = "/save.html", params = "json", method = RequestMethod.POST) 
    public @ResponseBody Map<String, ? extends Object> saveJSON(@RequestBody Location location, HttpServletResponse response) 
    { 
     Set<ConstraintViolation<Location>> errors = getValidator().validate(location); 
     Map<String, String> validationMessages = new HashMap<String, String>(); 
     if(!errors.isEmpty()) 
     { 
      //this map will contain the validation messages 
      validationMessages = validationMessages(errors); 

      //probably you would like to send the errors back to client 
      return validationMessages ; 
     } 
     else 
     { 
      //do whatever you like to do with the valid bean 

     } 
    } 

    public Map<String, String> validationMessages(Set<ConstraintViolation<Location>> failures) { 
     Map<String, String> failureMessages = new HashMap<String, String>(); 
     for (ConstraintViolation<Location> failure : failures) { 

       failureMessages.put(failure.getPropertyPath().toString(), failure.getMessage()); 
     } 
     return failureMessages; 
    } 



} 

в вашем яровой контексте файла добавьте следующий компонент

<beans:bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> 

надеюсь, что это помогает :)

+0

это работает как шарм. большое спасибо! – dtrunk