Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Revert to snippet with correct path. Example of using additional init-params.

...

As with the Codebehind Plugin, the first step is to tell the plugin where to find your resource action classes. Modify the configuration of your Struts 2 filter in web.xml and add the 'actionPackages' init-param like so:

Wiki Markup
{snippet:url=struts2/apps/rest-showcase/src/main/webapp/WEB-INF/web.xml|id=filter|lang=xml}
Code Block
langxml

To set other <filter>
Struts properties, add other init-params. For example  <filter-name>action2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
        to set {{devMode}} to true, add 
{code>
  <!-- ... -->
   <init-param>
        	<param-name>actionPackages<name>struts.devMode</param-name>
        	<param-value>org.apache.struts2.rest.example<value>true</param-value>
        </init-param>
    </filter>

Next, create Java objects ending in "Resource" in the configured package. The "Resource" suffix is used to distinguish Rest action resources from regular Struts 2 actions, although it is completely optional and they are functionally the same. Now, add in methods to handle the various requests. For example, the following resource action will support /orders/34 GET and PUT requests:

Code Block
langjava
package org.apache.struts2.rest.example;

public class OrdersController implements ModelDriven<Order> {

    private OrderManager orderManager;
    private String id;
    private Order model;
   
    // Handles /orders/{id} GET requests
    public HttpHeaders show() {
        model = orderManager.findOrder(id);
        return new DefaultHttpHeaders("show")
            .withETag(model.getUniqueStamp())
            .lastModified(model.getLastModified());
    }

    // Handles /orders/{id} PUT requests
    public String update() {
        orderManager.updateOrder(model);
        return "update";
    }

    // getters and setters
}

...