Enterprise Java

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Víctor Hernández
Víctor Hernández
9 years ago

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

Shyam
Shyam
9 years ago

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

Arun
Arun
9 years ago

Hi Biju,

Can you post the hotelRepository code which gives us more information how to take the value.

Since i read an article in Java Beat where they handling data in @XmlRootElement then showing in JSON format http://www.javabeat.net/spring-mvc-angularjs-integration/

Thanks in advance sharing your ideas.

-Arun

Back to top button