I have a Spring MVC application which communicates with the frontend with AJAX / JSON, and I have in the frontend a web application with HTML.
For adding an element to the database, I do this in the backend system:
@RequestMapping(value="add/", method=RequestMethod.POST)
public @ResponseBody SerializePerson addProject(@RequestBody Person person) {
Person p = this.personService.addPerson(person);
return new SerializePerson(p.getId(), p.getName(), p.getEmail());
}
But now I have the problem (this is a very simple example), that someone can create a project without a name, so the name = "" and a non valid email address. My problem is, that I want to validate the fields in the backend system.
So I found a Spring MVC showcase here: https://src.springsource.org/svn/spring-samples/mvc-showcase/src/main/java/org/springframework/samples/mvc/validation/
They do this:
@RequestMapping("/validate")
public @ResponseBody String validate(@Valid JavaBean bean, BindingResult result) {
if (result.hasErrors()) {
return "Object has validation errors";
} else {
return "No errors";
}
}
So, is this the best way? So I have to do two steps:
Isn't it possible to combine these two steps in one step? And how can I put the Person POST object from the frontend to the "validate" method in the backend and to see which field fails (name or email), because telling only "Object has validation errors" is not so good :-)?
Best Regards.
I did it shown in this example: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> create(@RequestBody Account account, HttpServletResponse response) {
Set<ConstraintViolation<Account>> failures = validator.validate(account);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
accounts.put(account.assignId(), account);
return Collections.singletonMap("id", account.getId());
}
}