Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PathVariable not binding with @RequestBody

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)
    {
        //...
    }
}
like image 950
dblank Avatar asked Oct 24 '13 00:10

dblank


1 Answers

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.

like image 69
Bargs Avatar answered Sep 20 '22 10:09

Bargs