Possible to modify @ModelAttribute before @Validat

2019-08-03 05:04发布

Is is possible to modify a @ModelAttribute before it is validated via @Validated.

ie

@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public final ModelAndView save(
        @Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject)

I need to change the state of myObject before @Validated is executed

1条回答
beautiful°
2楼-- · 2019-08-03 05:24

What about add a ModelAttribute populate method?

@ModelAttribute("myObject")
public MyObject modifyBeforeValidate(
        @ModelAttribute("myObject") MyObject myObject) {
    //modify it here
    return myObject;
}

The side affect is this method will be invoked before every @RequestMapping method if I'm not mistaken.

Update1: example

@ModelAttribute("command")
public ChangeOrderCommand fillinUser(
        @ModelAttribute("command") ChangeOrderCommand command,
        HttpServletRequest request) {
    command.setUser(securityGateway.getUserFrom(request));
    return command;
}

@RequestMapping(value = "/foo/bar", method = RequestMethod.POST)
public String change(@ModelAttribute("command") ChangeOrderCommand command,
        BindingResult bindingResult, Model model, Locale locale) {
}
查看更多
登录 后发表回答