Search code examples
spring-mvchibernate-validator

Possible to modify @ModelAttribute before @Validated is run


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


Solution

  • 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) {
    }