Angularjs ngResource是用于与基于REST的服务进行交互的angularjs模块。 我最近在Spring MVC的一个小型项目中使用了它,并希望记录一个对我来说很好的配置。
该控制器在工厂中运行,它支持在酒店实体上进行CRUD操作,并支持以下方法:
- POST / rest / hotels –创建一个酒店实体
- GET / rest / hotels –获取酒店实体列表
- GET / rest / hotels /:id –检索具有指定ID的实体
- PUT / rest / hotels /:id –更新实体
- DELETE / rest / hotels /:id –删除具有指定ID的实体
可以使用Spring MVC通过以下方式实现:
@RestController
@RequestMapping("/rest/hotels")
public class RestHotelController {private HotelRepository hotelRepository;@Autowiredpublic 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);}
}
注意@RestController批注,这是Spring Framework 4.0引入的新批注,在控制器上指定了此批注,可以避免每个方法上的@ResponseBody批注。
在angularjs端,可以使用以下方式在工厂中配置ngResource模块以使用此服务:
app.factory("Hotel", function ($resource) {return $resource("/rest/hotels", {id: "@id"}, {update: {method: 'PUT'}});
});
默认配置的唯一更改是使用PUT的Http方法而不是POST指定附加的“ update”操作。 进行此更改后,可以通过以下方式访问REST API:
POST / rest / hotels转换为:
var hotel = new Hotel({name:"test",address:"test address", zip:"0001"});
hotel.$save();
或其他的变化形式:
Hotel.save({}, {name:"test",address:"test address", zip:"0001"});
GET / rest / hotels转换为:
Hotel.query();
GET / rest / hotels /:id转换为:
Hotel.get({id:1})
PUT / rest / hotels /:id转换为:
var hotel = new Hotel({id:1, name:"test",address:"test address", zip:"0001"});
hotel.$update();
DELETE / rest / hotels /:id转换为:
var hotel = new Hotel({id:1});
hotel.$delete();
要么
Hotel.delete({id:1});
要处理成功和失败的结果,只需传入其他回调处理程序即可:
例如 与创建:
var hotel = new Hotel({name:"test",address:"test address", zip:"0001"});
hotel.$save({},function(response){//on success
}, function(failedResponse){//on failure
});
- 可以在以下github位置获得带有angularjs和Spring MVC的完整CRUD工作示例:https://github.com/bijukunjummen/spring-boot-mvc-test/tree/withangular
翻译自: https://www.javacodegeeks.com/2014/05/spring-rest-controller-with-angularjs-resource.html