2011-05-14 59 views
0

当我尝试将数据从控制器形成视图时弹出mvc 页加载我有问题。 这里是我的控制器:将模型数据加载到形成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("[email protected]"); 
     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"; 
    } 
} 

你有什么建议吗?谢谢!

回答

1

在处理POST请求期间,您不应该初始化此数据,因为它会覆盖用户提供的数据。相反,您应该在showAccountForm()中设置默认值。甚至更多:使用@ModelAttribute来填充模型。