spring mvc process object before @valid is applied

2019-07-01 13:35发布

I have a spring mvc controller like the following

@RequestMapping(value="/new", method=RequestMethod.POST)
public String createBooking(@Valid Booking booking, BindingResult bindingResult, Model model, Principal principal)
{
    if(bindingResult.hasErrors()) {
        return "booking/edit";
    }
    //Store Booking in db...
    ...

The problem is the Booking object i get from the POST is constructed by Spring, but one of the properties required by the validator cannot be populated, as the property is not present in the form. So my question is is there a way for me to intercept the Booking before it gets processed by the @Valid tag handler to add this required property?

Cheers! NFV

1条回答
唯我独甜
2楼-- · 2019-07-01 14:18

I'm not sure I understand the question, but it sounds like you want to set a field in the command object to a value before your command is bound by the form submission. If so, you can add a method in your controller as follows...

@ModelAttribute
public Booking getBooking() {
    Booking booking = new Booking();
    booking.setMyRequiredProperty("some value");
    return booking;
}

Hope that helps

查看更多
登录 后发表回答