Monday, April 15, 2013

Getting a List of resources in Spring MVC

Say you have a resource you are using already similar to this, but you want to be able to work with a list of them:
public class Person extends AbstractWebResource<Person> {

    public String getName() {
        return _name;
    }

    public void setName(String name) {
     _name= name;
    }
    
    @Column(name="name")
    private String _name;
}

The solution is to create a separate resource that is a list of your original resource:
public class BatchPersons {
    
    public void setPolicies(List<person> people) {
     _people = people;
    }
    
    public List<person> getPolicies() {
        return Collections.unmodifiableList(_people);
    }
       
    private List<person> _people;
}

Then, in the controller:
 @RequestMapping(method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.OK)
    public void put(@RequestBody BatchPersons resources)
            throws Exception {
        for (Person r : resources.getPolicies()) {
            //work with person
        }
    }

Now, you can make a PUT to your endpoint with a request payload as such:
{
    "people": [{
        "name": "Ned Stark"
    }, {
        "name": "Rob Stark"
    }]
}

No comments:

Post a Comment