0

spring MVC を使用して、エンティティにマップされないフォームを作成するにはどうすればよいですか (つまり、複数のエンティティからのプロパティがあります)。

エラーコレクションなどを持つ「結果」オブジェクトも検証して使用したいと思います。

これのオンラインの例はありますか?私はそれを理解するためにそれを見る必要があります(初心者)

4

1 に答える 1

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、BeanUtils、または同様のものを使用してDTOからドメインオブジェクトにデータを簡単に転送するには、おそらく合理的です。

于 2010-03-22T18:00:51.950 に答える