杩欎竴鑺傦紝鎴戜滑灞曠ず濡備綍閫氳繃 Spring Boot 鎻愪緵 Rest API锛屽苟浣跨敤 AngularJS 鏋勫缓鐣岄潰瀹炵幇涓�涓瀬绠�鐨� todo 搴旂敤銆�
鍏充簬 Rest API 鐨勪粙缁嶏紝鍙弬鑰� Rest API Tutorial.
鎻愪緵 TODO REST API
寮曞叆 Spring Data JPA 渚濊禆
鍦� build.gradle 涓姞鍏ヤ互涓嬩緷璧�:
...
runtime("com.h2database:h2")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
...
Spring Boot 榛樿鏀寔 H2, HSQLDB, SQLITE绛夊唴宓屾暟鎹簱鐨勬敮鎸侊紝鍙渶瑕佸彂鐜� classpath 涓湁瀵瑰簲 jar 鍖咃紝鍗冲彲姝g‘閰嶇疆鏁版嵁婧愩��
濡傞渶瑕佷娇鐢ㄥ叾浠栨暟鎹簱锛屽彲閫氳繃 application.properties 杩涜閰嶇疆锛屽:
spring.datasource.url=jdbc:mysql://localhost/demo?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
spring.datasource.username=devuser
spring.datasource.password=devuser
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
鍏充簬 Spirng Data JPA锛岃鍙傝�冨畼鏂规寚鍗�:
Spring Data JPA - Reference Documentation
缂栧啓 Todo.java
package li.fyunli.springboot.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
/**
* Created by fyunli on 16/4/2.
*/
@Entity
public class Todo implements Serializable {
private static final long serialVersionUID = 8277837190593516198L;
@Id
@GeneratedValue
private Long id;
@Column(length = 255, nullable = false)
private String content;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
缂栧啓 TodoRepository.java
package li.fyunli.springboot.repository;
import li.fyunli.springboot.entity.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Created by fyunli on 16/4/2.
*/
@Repository
public interface TodoRepository extends JpaRepository {
}
缂栧啓 TodoController.java
package li.fyunli.springboot.controller;
import li.fyunli.springboot.entity.Todo;
import li.fyunli.springboot.repository.TodoRepository;
import org.hibernate.ObjectNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by fyunli on 16/4/2.
*/
@RestController
@RequestMapping("/todos")
public class TodoController {
Logger logger = LoggerFactory.getLogger(TodoController.class);
@Resource
private TodoRepository repository;
@RequestMapping(method = RequestMethod.GET)
public List list() {
return this.repository.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Todo get(@PathVariable Long id) {
Todo todo = this.repository.findOne(id);
if (todo == null) {
throw new ObjectNotFoundException(id, Todo.class.toString());
}
return todo;
}
@RequestMapping(method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
public Todo create(@RequestBody Todo entity) {
logger.debug("create() with body {} of type {}", entity, entity.getClass());
return this.repository.save(entity);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = {MediaType.APPLICATION_JSON_VALUE})
public Todo update(@PathVariable Long id, @RequestBody Todo entity) {
logger.debug("update() of id#{} with body {}", id, entity);
return this.repository.save(entity);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable Long id) {
this.repository.delete(id);
}
}
鍚姩锛屾煡鐪嬬粨鏋�
浠ヤ笅鍐呭浣跨敤 postman 杩涜璋冭瘯銆�
- 鍒楀嚭 todo:
GET http://localhost:8080/todos
鍡紝褰撳墠娌℃湁 todo锛岄偅鎴戜滑灏卞垱寤轰竴涓惂銆�
鍒涘缓涔嬪悗锛宭ist 缁撴灉濡傚浘锛�
- 鍒涘缓 todo:
POST http://localhost:8080/todos
杈撳叆鍙傛暟鍜岀粨鏋滃鍥撅細
- 鏌ョ湅 id=? todo
GET http://localhost:8080/todos/1
- 鏇存柊 todo
PUT http://localhost:8080/todos/1
- 鍒犻櫎 todo
DELETE http://localhost:8080/todos/1
姝ゆ椂锛屽湪鏌ヨ id=1 鐨� todo锛岀粨鏋滃涓嬶細
浣跨敤 AngularJS 鏋勫缓椤甸潰
鍒涘缓鐢ㄦ埛鐣岄潰
鍦� src/resources/static 鍒涘缓 todoapp.html:
Spring Boot - todo
Spring Boot: TODO
There are no items yet.
鍦ㄦ锛屾垜浠�氳繃
鍛婄煡 AngularJS 鎴戜滑闇�瑕佸惎鐢� myApp 骞朵娇鐢� AppController銆�
鍒濆鍖� AngularJS
鍦� src/resources/static/app 娣诲姞 app.js
(function (angular) {
angular.module("myApp.controllers", []);
angular.module("myApp.services", []);
angular.module("myApp", ["ngResource", "myApp.controllers", "myApp.services"]);
}(angular));
鍦ㄦ锛屾垜浠畾涔変簡涓変釜 module: controllers, services, application锛屾敞鎰忥紝application 鍚嶅瓧蹇呴』鍜�
淇濇寔涓�鑷淬��
骞朵笖鎴戜滑璁� appliation 渚濊禆浜� ngResource, controllers, services.
鍒涘缓 resource factory
鍦� src/resources/static/app 娣诲姞 services.js
(function (angular) {
var ItemFactory = function ($resource) {
return $resource('/todos/:id', {
id: '@id'
}, {
update: {
method: "PUT"
},
remove: {
method: "DELETE"
}
});
};
ItemFactory.$inject = ['$resource'];
angular.module("myApp.services").factory("Item", ItemFactory);
}(angular));
鍦ㄦ閫氳繃 $resource (AngularJS resource framework) 鑷姩寮曞叆鏌ヨ锛屽垱寤哄姛鑳斤紝骞朵笖澹版槑鍔犲叆 update, remove 鍔熻兘銆�
鍒涘缓 AngularJS Controller
鍦� todoapp.html 涓垜浠湅鍒� ng-submit="addItem(newItem)" 绛夋寚浠わ紝涓嬮潰鎴戜滑鍦� src/resources/static/app 娣诲姞 controllers.js 杩涜瀹氫箟:
(function (angular) {
var AppController = function ($scope, Item) {
Item.query(function (response) {
$scope.items = response ? response : [];
});
$scope.addItem = function (content) {
new Item({
content: content,
checked: false
}).$save(function (item) {
$scope.items.push(item);
});
$scope.newItem = "";
};
$scope.updateItem = function (item) {
item.$update();
};
$scope.deleteItem = function (item) {
item.$remove(function () {
$scope.items.splice($scope.items.indexOf(item), 1);
});
};
};
AppController.$inject = ['$scope', 'Item'];
angular.module("myApp.controllers").controller("AppController", AppController);
}(angular));
娆h祻鎴愭灉
娴忚鍣ㄦ墦寮� http://localhost:8080/todoapp.html锛屾璧忔垚鏋滃惂锛�
婧愪唬鐮�
婧愪唬鐮侀摼鎺�: github