Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
xml
xml
<constant name="struts.convention.action.suffix" value="Controller"/>
<constant name="struts.convention.action.mapAllMatches" value="true"/>
<constant name="struts.convention.default.parent.package" value="rest-default"/>
<constant name="struts.convention.package.locators" value="example"/>

...

Write Your Controller Actions

Once everything is configured, you need to create the controllers. Controllers are simply actions created with the purpose of handling requests for a give RESTful resource. As we saw in the mapping logic above, various REST URL's will hit different methods on the controller. Traditionally, normal Struts 2 actions expose the execute method as their target method. Here's a sample controller for a orders resource. Note, it doesn't implement all of the possible REST URL to method mappings.

...

In this example, the ModelDriven interface is used to ensure that only my model, the Order object in this case, is returned to the client, otherwise, the whole OrdersController object would be serialized.

Note

Where's ActionSupport? Normally, you extend ActionSupport when writing Struts 2 actions. In these case, our controller doesn't do that. Why, you ask? ActionSupport provides a bunch of important functionality to our actions, including support for i18n and validation. All of this functionality, in the RESTful case, is provided by the default interceptor stack defined in the REST plugin's struts-plugin.xml file. Unless you willfully break your controller's membership in the rest-default package in which that stack is defined, then you'll get all that functionality you are used to inheriting from ActionSupport.

You may wonder why the show() method returns a HttpHeaders object and the update() method returns the expected result code String. The REST Plugin adds support for action methods that return HttpHeaders objects as a way for the action to have more control over the response. In this example, we wanted to ensure the response included the ETag header and a last modified date so that the information will be cached properly by the client. The HttpHeaders object is a convenient way to control the response in a type-safe way.

...