...
- Ruby on Rails REST-style URLs
- Zero XML config when used with Convention Plugin
- Built-in serialization and deserialization support for XML and JSON
- Automatic error handling
- Type-safe configuration of the HTTP response
- Automatic conditional GET support
...
Mapping REST URLs to Struts 2 Actions
The main functionality of the REST plugin lies in the interpretation of incoming request URL's according the RESTful rules. In the Struts 2 framework, this 'mapping' of request URL's to Actions is handled by in implementation of the ActionMapper
interface. Out of the box, Struts 2 uses the DefaultActionMapper
to map URL's to Actions via the logic you are probably already familiar with.
...
The REST plugin automatically handles serialization to, and deserialization from, each format.
Usage
This section will walk you through a quick demo.
Set Up
Assuming you have a normal Struts 2 application, all you need to do for this REST demo is to add the following two plugins:
*Struts 2 Rest Plugin
*Struts 2 Convention Plugin
Create Controller Actions
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 First, create your Controller classes. Note, Actions normally expose the execute
method to as their target method. Controllers expose a different set of methods, indicated in the RESTful URL to controller/method logic described above. For example, the following resource action will support /orders/34
GET and PUT requests:on the other hand . . .
Code Block | ||
---|---|---|
| ||
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 } |
...