I have a problem when I try put data from controller to form view when page load in spring mvc.
Here is my Controller:
@Controller
@RequestMapping("myaccount.htm")
public class MyAccountController {
@Autowired
private AccountValidation accountValidation;
public void setAccountValidation(AccountValidation accountValidation){
this.accountValidation = accountValidation;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringUTF8Editor(true));
}
@RequestMapping(method = RequestMethod.GET)
public String showAccountForm(Map<String, AccountForm> model){
AccountForm account = new AccountForm();
model.put("accountform", account);
return "myaccount";
}
@RequestMapping(method = RequestMethod.POST)
public String processAccount(@Valid AccountForm accountForm,
BindingResult result, Map<String, AccountForm> model, HttpSession session, HttpServletResponse response) {
//I try put something model like this when load page
AccountForm acc = new AccountForm();
acc.setEmail("h@gmail.com");
acc.setBirth("12/12/1989");
acc.setPassword("user");
acc.setPhone(21767621);
// but it only show when I submit
model.put("accountform", acc);
if(result.hasErrors()){
return "myaccount";
}
return "myaccount";
}
}
Do you have any suggestions? Thanks!
You should not initialize this data during processing POST request, because it overwrites user’s supplied data. Instead you should set default values in
showAccountForm(). And even more: use@ModelAttributeto fill model.