当我在spring mvc中页面加载时尝试将数据从控制器放入表单视图时出现问题。 这是我的控制器:
@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";
}
}
你有什么建议吗?谢谢!
答案 0 :(得分:1)
在处理POST请求期间,您不应初始化此数据,因为它会覆盖用户提供的数据。相反,您应该在showAccountForm()
中设置默认值。甚至更多:使用@ModelAttribute
来填充模型。