2008/04/15からのアクセス回数 6806
mvc-conventionの例題は、Recipeの追加削除ができません。 ここでは、RecipeのCRUD(Create, Read, Update, Delete)機能を追加します。
最初に、EditRecipeControllerのformBackingObjectを変更します。 新規のRecipeの追加の場合には、idがセットされていませんので、idがHTTP要求に ない場合の処理を追加します。
protected Object formBackingObject(HttpServletRequest request) throws Exception { try { long id = ServletRequestUtils.getRequiredLongParameter(request, "id"); Recipe recipe = this.recipeManager.findById(new Long(id)); return recipe; } catch (MissingServletRequestParameterException e) { Recipe recipe = new Recipe(); return recipe; } }
次に、SwitchBoardControllerにdeleteメソッドを追加します。
deleteメソッドでは削除した後switchboard/listRecipesに画面を遷移しますので、 モデルにrecipeListを追加する必要があります。
deleteメソッドは、以下のようになります。
public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception { long id = ServletRequestUtils.getRequiredIntParameter(request, "id"); Recipe recipe = recipeManager.findById(new Long(id)); ((IRecipeDao)recipeManager).delete(recipe); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject(recipeManager.findAll()); modelAndView.setViewName("switchboard/listRecipes"); return modelAndView; }
ここで、recipeManagerを、移植のためStubRecipeDaoManagerに代えましたが、型宣言は RecipdeManagerのままなので、以下のように IRecipeDaoのインタフェースを使用するためにIRecipeDaoでキャストします。
((IRecipeDao)recipeManager).delete(recipe);
これでコントローラの処理は完了です。
削除リンクの追加は、編集リンクと同様に
#set( $deleteLink = "/switchboard/delete.htm?id=${recipe.id}" ) <td><a href="#springUrl(${deleteLink})">[delete]</a></td>
とします。
新規追加リンクは、idを指定しないでeditrecipe.htmに遷移させます。
<a href='#springUrl("/editrecipe.htm")'>add</a>
修正されたlistRecipes.vmは以下にあります。
recipe.idがセットされていないときには、HTTPのPOST処理でidが送信されないようにするために、 以下のようにif文を入れます。
#if ( $recipe.id ) <input type="hidden" name="id" value="$!recipe.id"> #end
$recipe.idがnullでないときのみidをhiddenにセットします。
修正されたeditRecipe.vmは以下にあります。
mavenのjettyプラグインを起動します。
$ jetty:run
次にブラウザーで
http://localhost:8080/mvc-convention/
と入力すると以下の画面に代わります。
addリンクをクリックするとNameのテキスト入力が空の画面になります。
テストと入力して、Save Changeボタンを押すと、テストがリストに追加されています。
最後に、deleteリンクを押すとテストが削除されて、最初のリスト画面になります。
この記事は、
皆様のご意見、ご希望をお待ちしております。