spring mvc process object before @valid is applied

拟墨画扇 提交于 2020-01-04 02:54:56

问题


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:


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



来源:https://stackoverflow.com/questions/14732598/spring-mvc-process-object-before-valid-is-applied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!