- 追加された行はこの色です。
- 削除された行はこの色です。
[[FrontPage]]
* Cart問題 [#c949db9e]
Agile Web Development with Railsの例題と同じ問題をSpringを使って実装を試みたときの
メモです。
もう一つの目的は、Spring-MVCプラグインがどの程度実際の問題解決に役立つかを検証することです。
** プロジェクトの作成 [#y8873d2a]
mavenを使ってプロジェクトを生成します。
- groupIdは、example.cart
- artifactIdは、cart
とします。ecliseでプロジェクトを管理できるようにeclipseプラグインも起動します。
#pre{{
mvn archetype:create \
-DgroupId=example.cart \
-DartifactId=cart \
-DarchetypeArtifactId=spring-mvc-archetype \
-DarchetypeGroupId=jp.co.pwv.spring-mvc-archetype \
-DarchetypeVersion=1.1.1
cd cart
mvn eclipse:eclipse -DdownloadSources=true
}}
データベースは、HsqlDBのサーバを使用するため、db.propertiesの内容を修正します。
#pre{{
db.url=jdbc:hsqldb:hsql://localhost
}}
最後にeclipseでcartプロジェクトをimportし、CVSに登録します。
** session scopeの確認 [#w1b0d28a]
cartはセッションの中で管理しなければなりません。そのため、Spring2.0から導入されたsession scopeを使用します。
まずは、session scopeの使い方を確認します。session, request scopeを使うために、以下の定義をweb.xmlに追加します。
まずは、session scopeの使い方を確認します。
最初に以下のような簡単なクラスを定義します。
#pre{{
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
package example.cart.service;
public class CartService {
private Integer id;
public CartService() {
id = new Integer(1);
}
}
}}
session scopeオブジェクトは、サーブレットではなく、applicationContext.xmlと同レベルで定義しないとbeanが見つからないとのエラーになります。
そこで、session-def.xmlにsession scopeをまとめて定義しました。
#pre{{
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- a HTTP Session-scoped bean exposed as a proxy -->
<bean id="cartService" class="example.cart.service.CartService" scope="session" />
</beans>
}}
本当は、<aop:scoped-proxy />を使って自動的にsession scopeオブジェクトの再配置をしたかったのですが、何度もテストしましたがこの宣言を入れるとうまくオブジェクトがセットされません。
次にこのsession scopeオブジェクトを使用するメソッド(ここではlistメソッド)に
#pre{{
ApplicationContext co = WebApplicationContextUtils.getRequiredWebApplicationContext( request.getSession().getServletContext());
Object obj = co.getBean("cartService");
}}
としてアプリケーション・コンテキストからcartServiceを取得します。
次に、デバッガでCartServiceのコンストラクタにブレークポイントをセットし、tomcatを起動します。
ブラウザーからlistのページにアクセスするとcartServiceオブジェクトのコンストラクタがコールされます。
ブラウザーを起動し直すと再度cartServiceオブジェクトのコンストラクタがコールされ、session毎に
オブジェクトが生成されることが確認できます。