Reputation: 38573
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
Upvotes: 1
Views: 1304
Reputation: 26848
There are 2 ways to modify the model attribute object before the @Validated
will trigger:
@Validated
and autowire the validator and manually trigger the validator:class MyController {
private final Validator validator;
class MyController(Validator validator) {
this.validator = validator;
}
@PostMapping("/doSomething")
public final ModelAndView save(
@ModelAttribute("myObject") MyObject myObject, BindingResult result) {
// edit MyObject here
validator.validate(myObject, result)
// original method body here
}
myObject
object inside the decorated validator.class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setValidator(new PreProcessMyObjectValidator(binder.getValidator()));
}
@PostMapping("/doSomething")
public final ModelAndView save(
@Validated(value = {myGroup.class}) @ModelAttribute("myObject") MyObject myObject, BindingResult result) {
...
}
private static class PreProcessMyObjectValidator implements Validator {
private final Validator validator;
public PreProcessMyObjectValidator(Validator validator) {
this.validator = validator;
}
@Override
public boolean supports(@Nonnull Class<?> clazz) {
return validator.supports(clazz);
}
@Override
public void validate(@Nonnull Object target, @Nonnull Errors errors) {
if (target instanceof MyObject) {
MyObject myObject = (MyObject) target;
// manipulate myObject here
}
validator.validate(target, errors);
}
}
}
(This second tip is what I picked up from https://github.com/spring-projects/spring-framework/issues/11103)
Upvotes: 0
Reputation: 7283
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) {
}
Upvotes: 1