Skip to content
josedonizetti edited this page Feb 9, 2011 · 21 revisions

One minute tutorial

Let's write an simple application, that render an item resource represented as xml. We will have one entry point that list all items, and which item will have an hypermedia link to render itself;

Server side

Download VRaptor blank application, so that you have the server application with all jars configured and ready to start. First we will create a VRaptor controller, on it we will say which uri we may respond, and how will the items be returned. At this example we will use an class to simulate the database, you can have it at Database.java.

   @Resource
   public class ItemsController {
       
        private final Result result;        
        private final Database database;

        public ItemController(Result result){
           this.result = result;
           this.database = new Database();
        }
        
        @Get
        @Path("/items")
        public void list(){
           result.use(xml()).from(database.getItems()).serialize();
        }

        @Get
        @Path("/items/{id}")
        public void show(Integer id){
           //because list are zero-baed
           Item item = database.getItem(id);
           result.use(xml()).from(item).serialize();
        }

   }

Although the controller would generate our xml, it is not aware about the hypermedia links the resource contains. So we must configure our item object, for it to genereate which hypermedia links must be returned.

  public class Item implements HypermediaResource {

    private Integer id;
    private String name;
    private Double price;

    public Item(Integer id, String name, Double price){
       this.id = id;
       this.name = name;
       this.price = price; 
    }

   public void configureRelations(RelationBuilder builder) {
        builder.relation("self").uses(ItemsController.class).show(id);
   }
   }     
Clone this wiki locally