javascript
带有AngularJS资源的Spring Rest Controller
Angularjs ngResource是用于與基于REST的服務進行交互的angularjs模塊。 我最近在Spring MVC的一個小型項目中使用了它,并希望記錄一個對我來說很好的配置。
該控制器在工廠中運行,它支持在Hotel實體上進行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
總結
以上是生活随笔為你收集整理的带有AngularJS资源的Spring Rest Controller的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网易+我的世界+电脑配置(我的世界网易版
- 下一篇: 使用Mocks进行需求驱动的软件开发