[[Spring-MVC/ステップ・バイ・ステップ]]

2008/04/15からのアクセス回数 &counter;

#contents

mvc-conventionの例題は、Recipeの追加削除ができません。
ここでは、RecipeのCRUD(Create, Read, Update, Delete)機能が使えるように変更します。

** コントローラの変更 [#y1bf528a]
*** EditRecipeControllerの変更 [#redd0a81]
最初に、EditRecipeControllerのformBackingObjectを変更します。
新規のRecipeの追加の場合には、idがセットされていませんので、idがHTTP要求に
ない場合の処理を追加します。

#pre{{
    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の変更 [#t6aff2ef]
次に、SwitchBoardControllerにdeleteメソッドを追加します。

deleteメソッドでは削除した後switchboard/listRecipesに画面を遷移しますので、
モデルにrecipeListを追加する必要があります。

deleteメソッドは、以下のようになります。

#pre{{
    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);

これでコントローラの処理は完了です。

** ビューの変更 [#tdd302de]
*** listRecipes.vmの変更 [#i5eaaecc]
削除リンクの追加は、編集リンクと同様に

#pre{{
            #set( $deleteLink = "/switchboard/delete.htm?id=${recipe.id}" )
            <td><a href="#springUrl(${deleteLink})">[delete]</a></td>
}}
とします。

新規追加リンクは、idを指定しないでeditrecipe.htmに遷移させます。

#pre{{
<a href='#springUrl("/editrecipe.htm")'>add</a>
}}

修正されたlistRecipes.vmは以下にあります。
#ref(listRecipes.vm);

*** editRecipe.vmの変更 [#h1fd49a0]
recipe.idがセットされていないときには、HTTPのPOST処理でidが送信されないようにするために、
以下のようにif文を入れます。

#pre{{
#if ( $recipe.id )
		<input type="hidden" name="id" value="$!recipe.id">
#end
}}

$recipe.idがnullでないときのみidをhiddenにセットします。

修正されたeditRecipe.vmは以下にあります。
#ref(editRecipe.vm);

** 動作確認 [#d83aa63c]
mavenのjettyプラグインを起動します。

#pre{{
$ jetty:run
}}

次にブラウザーで
#pre{{
http://localhost:8080/mvc-convention/
}}

と入力すると以下の画面に代わります。

#ref(listRecipe.jpg);

addリンクをクリックするとNameのテキスト入力が空の画面になります。

#ref(editrecipe.jpg);

テストと入力して、Save Changeボタンを押すと、テストがリストに追加されています。

#ref(listRecipe2.jpg);

最後に、deleteリンクを押すとテストが削除されて、最初のリスト画面になります。

** コメント [#qd1a2ff6]
この記事は、

#vote(おもしろかった,そうでもない,わかりずらい)
#vote(おもしろかった[1],そうでもない[0],わかりずらい[0])

皆様のご意見、ご希望をお待ちしております。

#comment


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
SmartDoc