2010-03-19 51 views
0

使用spring MVC,我將如何創建一個不映射到實體的表單(即它具有來自多個實體的屬性)。創建一個不映射到實體的表單

我也想驗證和使用有錯誤收集等

的這個任何網上的例子他們的「結果」的對象?我需要看它來了解它(新手)

回答

0

您只需創建一個包含表單所需的所有屬性的新類,並將其用作表單的模型屬性。在接聽電話中,您也可以使用此類型。 Spring會自動爲你綁定屬性。您還應該考慮使用JSR-303驗證註釋。

一般的方法是加載所有必要的實體以從GET請求創建窗體支持對象。然後,您將該表單支持對象放入模型中。在POST/PUT請求上,您必須重新構建實際觸摸的實體。通常,您再次加載它們,然後將新提交的部分數據應用於它們。

一般來說,構建一個專用組件來處理組裝行爲對於您來說不會污染具有該代碼的控制器可能是一個好主意。

/** 
* Prepares the form by setting up a custom form backing object. 
*/ 
@RequestMapping(value = "account/{id}", method = GET) 
public String processGet(@PathVariable("id") Long id, Model model) { 

    Account account = accountService.getAccount(id); 
    return prepareForm(dtoAssembler.createFormFor(account), model); 
} 


/** 
* Process form submission. Uses JSR-303 validation and explicit error 
* handling. 
*/ 
@RequestMapping(value = "account/{id}", method = PUT) 
public String processGet(@ModelAttribute("accountForm") @Valid AccountForm form, Errors errors, Model model) { 

    if (errors.hasErrors()) { 
    return prepareForm(form, model); 
    } 

    Account account = accountService.getAccount(form.getId()); 
    accountService.save(dtoAssembler.applyData(account, form)); 

    return "redirect:/accounts"; 
} 


/** 
* Populates the given {@code Model} with the given {@code AccountForm} 
* and returns the view to show the form. 
*/  
private String prepareForm(AccountForm form, Model model) { 
    model.addAttribute("accountForm", form); 
    return "account"; 
} 

我只是寫這樣說這裏要強調這是怎麼回事。在真實世界的場景中,我可能會讓DtoAssembler完成與該服務的所有工作(所以我會將該服務注入彙編程序)。

爲了便於使用Dozer將數據從DTO傳輸到域對象,BeanUtils或類似的東西可能是合理的。

+0

所以在獲取請求時,我會加載實體,然後加載包含表單屬性的類。在帖子上,我會做什麼? (小僞代碼可能?)謝謝! – Blankman 2010-03-22 18:44:48

+0

關於您的評論更新了我的文章:) – 2010-03-26 12:06:53