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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

2 Responses 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.

  2. Shyam says:

    Hi Biju ,

    Thanks for posting this tutorial .

    I was reading through the code , have a question can you please explain the code pasted below . Where exactly are they pointing to ?

    Thanks,
    -Shyam

Leave a Reply


1 + = seven



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close