Spring Rest Controller with angularjs resource

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
Reference: Spring Rest Controller with angularjs resource from our JCG partner Biju Kunjummen at the all and sundry blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Spring Rest Controller with angularjs resource"

  1. Víctor Hernández says:

    hi, very good tutorial, congratulate you, have a problem, I can import it into eclipse, a must do?, Thanks.

Leave a Reply


4 − four =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books