2011-05-14 47 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來填充模型。