カウントするサンプル
Say for example that we want to count the number of requests in a session. Define a Counter object which will live on the session:
例として、セッション中のリクエストの数を数える機能を持ったサンプルを挙げましょう。Sessionの中で有効なCounterオブジェクトを定義します。
@SessionScoped public class Counter { int count = 0; /** Increments the count and returns the new value. */ public synchronized int increment() { return count++; } }
Next, we can inject our counter into an action:
次に、アクションの中にカウンターをインジェクトしましょう。
public class Count { final Counter counter; @Inject public Count(Counter counter) { this.counter = counter; } public String execute() { return SUCCESS; } public int getCount() { return counter.increment(); } }
Then create a mapping for our action in our struts.xml file:
それから、struts.xmlファイルの中で、このアクションのマッピングを記述します。
<action name="Count" class="mypackage.Count"> <result>/WEB-INF/Counter.jsp</result> </action>
And a JSP to render the result:
そして、以下は結果を描画するJSPです。
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <body> <h1>Counter Example</h1> <h3><b>Hits in this session:</b> <s:property value="count"/></h3> </body> </html>
We actually made this example more complicated than necessary in an attempt to illustrate more concepts. In reality, we could have done away with the separate Counter object and applied @SessionScoped to our action directly.
実は、より多くの概念を明らかにするための試みとして、このサンプルは必要以上に複雑にしています。
現実では、別々のCounterオブジェクトではなく、直接@SessionScopedをActionに適用します。