Locked History Actions

Diff for "guice/Manual/Integration/Struts2Integration"

Differences between revisions 1 and 2
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
Struts 2 Integration = Struts 2との統合 =
Line 4: Line 4:
{{{
Line 6: Line 6:
}}}
Line 8: Line 8:
{{{
Line 10: Line 10:
}}}
Line 15: Line 15:
{{{
Line 26: Line 26:
}}}
Line 28: Line 28:
{{{
Line 46: Line 46:
}}}
Line 48: Line 48:
{{{
Line 53: Line 53:
}}}
Line 55: Line 55:
{{{
Line 65: Line 65:
}}}

Struts 2との統合

To install the Guice Struts 2 plugin with Struts 2.0.6 or later, simply include guice-struts2-plugin-1.0.jar in your web application's classpath and select Guice as your ObjectFactory implementation in your struts.xml file:

<constant name="struts.objectFactory" value="guice" />

Guice will inject all of your Struts 2 objects including actions and interceptors. You can even scope your actions. You can optionally specify a Module for Guice to install in your struts.xml file:

<constant name="guice.module" value="mypackage.MyModule"/>

If all of your bindings are implicit, you can get away without defining a module at all. A Counting Example

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:

@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:

<action name="Count"
    class="mypackage.Count">
  <result>/WEB-INF/Counter.jsp</result>
</action>     

And a JSP to render the result:

<%@ 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.