這一節(jié)瞎颗,我們展示如何通過 Spring Boot 提供 Rest API笙以,并使用 AngularJS 構(gòu)建界面實現(xiàn)一個極簡的 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等內(nèi)嵌數(shù)據(jù)庫的支持溉知,只需要發(fā)現(xiàn) classpath 中有對應 jar 包陨瘩,即可正確配置數(shù)據(jù)源。
如需要使用其他數(shù)據(jù)庫级乍,可通過 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<Todo, Long> {
}
編寫 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<Todo> 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);
}
}
啟動卡者,查看結(jié)果
以下內(nèi)容使用 postman 進行調(diào)試蒿囤。
- 列出 todo:
GET http://localhost:8080/todos
嗯,當前沒有 todo崇决,那我們就創(chuàng)建一個吧材诽。
創(chuàng)建之后,list 結(jié)果如圖:
- 創(chuàng)建 todo:
POST http://localhost:8080/todos
輸入?yún)?shù)和結(jié)果如圖:
- 查看 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脸侥,結(jié)果如下:
使用 AngularJS 構(gòu)建頁面
創(chuàng)建用戶界面
在 src/resources/static 創(chuàng)建 todoapp.html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="fyunli">
<title>Spring Boot - todo</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://cdn.jsdelivr.net/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="http://cdn.jsdelivr.net/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body ng-app="myApp">
<div class="container" ng-controller="AppController">
<div class="page-header">
<h1>Spring Boot: TODO</h1>
</div>
<div class="alert alert-info" role="alert" ng-hide="items && items.length > 0">
There are no items yet.
</div>
<form class="form-horizontal" role="form" ng-submit="addItem(newItem)">
<div class="form-group" ng-repeat="item in items">
<div class="checkbox col-xs-9">
<label>
<input type="checkbox" ng-model="item.checked" ng-change="updateItem(item)"/> {{item.content}}
</label>
</div>
<div class="col-xs-3">
<button class="pull-right btn btn-danger" type="button" title="Delete"
ng-click="deleteItem(item)">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
</div>
<hr/>
<div class="input-group">
<input type="text" class="form-control" ng-model="newItem" placeholder="Enter the content..."/>
<span class="input-group-btn">
<button class="btn btn-default" type="submit" ng-disabled="!newItem" title="Add">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
</div>
<footer class="footer">
<div class="container">
<p class="text-muted">©2016 fyunli</p>
</div>
</footer>
<script src="http://cdn.jsdelivr.net/angularjs/1.5.0/angular.min.js"></script>
<script src="http://cdn.jsdelivr.net/angularjs/1.5.0/angular-resource.min.js"></script>
<script src="http://cdn.jsdelivr.net/lodash/4.7.0/lodash.min.js"></script>
<script type="text/javascript" src="./app/app.js"></script>
<script type="text/javascript" src="./app/controllers.js"></script>
<script type="text/javascript" src="./app/services.js"></script>
</body>
</html>
在此,我們通過
<body ng-app="myApp">
<div class="container" ng-controller="AppController">
告知 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 名字必須和 <body ng-app="myApp"> 保持一致外遇。
并且我們讓 appliation 依賴于 ngResource, controllers, services.
創(chuàng)建 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) 自動引入查詢,創(chuàng)建功能契吉,并且聲明加入 update, remove 功能跳仿。
創(chuàng)建 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));
欣賞成果
瀏覽器打開 http://localhost:8080/todoapp.html捐晶,欣賞成果吧:
源代碼
源代碼鏈接: github