Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Rest Controller with angularjs $resource

DZone's Guide to

Spring Rest Controller with angularjs $resource

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

Angularjs ngResource is an angularjs module for interacting with REST based services. I used it recently for a small project with Spring MVC and wanted to document a configuration that worked well for me.


The controller is run of the mill, it supports CRUD operations on a Hotel entity and supports the following methods:


POST /rest/hotels - creates a Hotel entity

GET /rest/hotels - gets the list of Hotel entities

GET /rest/hotels/:id - retrieves an entity with specified Id

PUT /rest/hotels/:id - updates an entity

DELETE /rest/hotels/:id - deletes an entity with the specified id


This can implemented in the following way using Spring MVC:


@RestController
@RequestMapping("/rest/hotels")
public class RestHotelController {
 private HotelRepository hotelRepository;

 @Autowired
 public RestHotelController(HotelRepository hotelRepository) {
  this.hotelRepository = hotelRepository;
 }

 @RequestMapping(method=RequestMethod.POST)
 public Hotel create(@RequestBody @Valid Hotel hotel) {
  return this.hotelRepository.save(hotel);
 }

 @RequestMapping(method=RequestMethod.GET)
 public List<Hotel> list() {
  return this.hotelRepository.findAll();
 }

 @RequestMapping(value="/{id}", method=RequestMethod.GET)
 public Hotel get(@PathVariable("id") long id) {
  return this.hotelRepository.findOne(id);
 }

 @RequestMapping(value="/{id}", method=RequestMethod.PUT)
 public Hotel update(@PathVariable("id") long id, @RequestBody @Valid Hotel hotel) {
  return hotelRepository.save(hotel);
 }

 @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
 public ResponseEntity<Boolean> delete(@PathVariable("id") long id) {
  this.hotelRepository.delete(id);
  return new ResponseEntity<Boolean>(Boolean.TRUE, HttpStatus.OK);
 }
}

Note the @RestController annotation, this is a new annotation introduced with Spring Framework 4.0, with this annotation specified on the controller, the @ResponseBody annotation on each of the methods can be avoided.


On the angularjs side, the ngResource module can be configured in a factory the following way, to consume this service:


app.factory("Hotel", function ($resource) {
    return $resource("/rest/hotels", {id: "@id"}, {
        update: {
            method: 'PUT'
        }
    });
});

The only change to the default configuration is in specifying the additional "update" action with the Http method of PUT instead of POST. With this change, the REST API can be accessed the following way:


POST /rest/hotels translates to:


var hotel = new Hotel({name:"test",address:"test address", zip:"0001"});
hotel.$save();

Or another variation of this:

Hotel.save({}, {name:"test",address:"test address", zip:"0001"});

GET /rest/hotels translates to :

Hotel.query();

GET /rest/hotels/:id translates to :

Hotel.get({id:1})

PUT /rest/hotels/:id translates to :


var hotel = new Hotel({id:1, name:"test",address:"test address", zip:"0001"});
hotel.$update();


DELETE /rest/hotels/:id translates to:


var hotel = new Hotel({id:1});
hotel.$delete();

OR

Hotel.delete({id:1});

To handle successful and failure outcomes just pass in additional callback handlers:


for eg. with create:

var hotel = new Hotel({name:"test",address:"test address", zip:"0001"});
hotel.$save({},function(response){
//on success
}, function(failedResponse){
//on failure
});

A complete CRUD working sample with angularjs and Spring MVC is available at this github location: https://github.com/bijukunjummen/spring-boot-mvc-test/tree/withangular

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
java ,frameworks ,javascript ,tips and tricks ,angular

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}