When I don't use @RequestBody the @PathVariable id is automatically set at my Entity class. But if I use @RequestBody it's not. I need that the id of Entity is set before my GenericValidator executes validation. Why does it work without @RequestBody and not with it?
The Entity class:
public class Entity {
    private String id;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    //...
}
The controller class:
@Controller
@RequestMapping(value = "/entity")
public class EntityController {
    @Autowired
    private GenericValidator validator;
    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.addValidators(validator);
    }
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public @ResponseBody Response update(
            @PathVariable String id,
            @Valid @RequestBody Entity entity)
    {
        //...
    }
}
                When used alone, @Valid works much like @ModelAttribute. The Entity method argument would be retrieved from the Model or instantiated, the WebDataBinder would handle the data binding process (this is when the id would be set), and then validation would occur.
@RequestBody arguments do not go through the data binding process like @ModelAttribute arguments. They're created via an HttpMessageConverter using the body of the request instead of matching the names of request parameters and path variables to the names of your object's fields. When combined with @Valid, the configured validator is run against the new object but @ModelAttribute style data binding still does not occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With