I have a registration form in my header.jsp which includes fields; name-email-password.
When user clicks "register" button, it will be POSTed to my registration controller:
@RequestMapping(value ="/register", method = RequestMethod.POST)
public String registerUserAccount(@Valid @ModelAttribute("user") RegistrationForm userAccountData,
BindingResult result, ... )
Since I'm using spring form tag, I include an empty user object for data binding in my index view.
The problem is I keep getting
Neither BindingResult nor plain target object for bean name 'user' available as request attribute
This form resides in my header file, so it is accessible from all pages. Do I have to add a user object to every ModelAndView
or is there a neater way to tackle this problem.
You can to do the following:
@ControllerAdvice
public class ModelAdvice {
@ModelAttribute
public RegistrationForm registrationForm() {
return new RegistrationForm();
}
}
@ControllerAdvice
is used when you want something to apply to all controllers. In this case you want to apply the @ModelAttribute
to all the controllers since as you say the registration form is in all the pages.
For more find grained control, you would probably want to implement a HandlerInterceptor that would add to the the required data to HttpServletRequest
when needed