リポジトリをWebレイヤーでラップするには、Spring MVCを使用する必要があります。Spring Bootのおかげで、基本的なコードはほとんど書くことができません。代わりに、操作に集中できます。
nonrest/src/main/java/payroll/EmployeeController.java
package payroll;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
class EmployeeController {
private final EmployeeRepository repository;
EmployeeController(EmployeeRepository repository) {
this.repository = repository;
}
// Aggregate root
@GetMapping("/employees")
List<Employee> all() {
return repository.findAll();
}
@PostMapping("/employees")
Employee newEmployee(@RequestBody Employee newEmployee) {
return repository.save(newEmployee);
}
// Single item
@GetMapping("/employees/{id}")
Employee one(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new EmployeeNotFoundException(id));
}
@PutMapping("/employees/{id}")
Employee replaceEmployee(@RequestBody Employee newEmployee, @PathVariable Long id) {
return repository.findById(id)
.map(employee -> {
employee.setName(newEmployee.getName());
employee.setRole(newEmployee.getRole());
return repository.save(employee);
})
.orElseGet(() -> {
newEmployee.setId(id);
return repository.save(newEmployee);
});
}
@DeleteMapping("/employees/{id}")
void deleteEmployee(@PathVariable Long id) {
repository.deleteById(id);
}
}
@RestController
つまり、各メソッドによって返されるデータは、テンプレートをレンダリングするのではなく、応答本文に直接書き込まれます。EmployeeRepository
コンストラクターによってコントローラーに注入されます。- 我々は、ルーティングを提供
@GetMapping
(するための各操作@PostMapping
、@PutMapping
及び@DeleteMapping
、HTTPに対応しGET
、POST
、PUT
およびDELETE
コール)。(注:各メソッドを読み、その役割を理解することは非常に役立ちます。); EmployeeNotFoundException
例外は、いつ従業員を見つけるべきかを示すのに使用されますが、従業員を見つけることができません。
nonrest/src/main/java/payroll/EmployeeNotFoundException.java
package payroll;
class EmployeeNotFoundException extends RuntimeException {
EmployeeNotFoundException(Long id) {
super("Could not find employee " + id);
}
}
投げたときEmployeeNotFoundException
と、レンダリングのための本の追加シーンのSpring MVCの構成HTTP 404:
nonrest/src/main/java/payroll/EmployeeNotFoundAdvice.java
package payroll;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
class EmployeeNotFoundAdvice {
@ResponseBody
@ExceptionHandler(EmployeeNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
String employeeNotFoundHandler(EmployeeNotFoundException ex) {
return ex.getMessage();
}
}
@ResponseBody
提案が応答本文で直接提示されることを示します。@ExceptionHandler
推奨構成はのみスローされEmployeeNotFoundException
、応答のみ。@ResponseStatus
送信HttpStatus.NOT_FOUND
するとは、つまりHTTP 404です。- 提案されたトピックはコンテンツを生成します。この場合、例外メッセージが表示されます。
使用を開始するには、右スタンドアロンPayRollApplication
でのpublic static void main
、そして中にIDEから選択するファイル名を指定して実行、または:
Spring InitializrはMavenラッパーを使用するため、次のように入力します。
$ ./mvnw clean spring-boot:run
または、インストールしたMavenバージョンを使用して次のコマンドを入力します。
$ mvn clean spring-boot:run
アプリケーションが起動したら、すぐにクエリを実行できます。
$ curl -v localhost:8080/employees
これにより以下が生成されます:
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /employees HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Thu, 09 Aug 2018 17:58:00 GMT
<
* Connection #0 to host localhost left intact
[{"id":1,"name":"Bilbo Baggins","role":"burglar"},{"id":2,"name":"Frodo Baggins","role":"thief"}]
ここでは、プリロードされたデータを圧縮形式で表示できます。
存在しないユーザーをクエリしようとすると...
$ curl -v localhost:8080/employees/99
取得します:
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /employees/99 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 404
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 26
< Date: Thu, 09 Aug 2018 18:00:56 GMT
<
* Connection #0 to host localhost left intact
Could not find employee 99
メッセージはHTTP 404エラーを適切に示し、カスタムメッセージは従業員99を見つけることができません。
現在コーディングされている対話を表示することは難しくありません...
$ curl -X POST localhost:8080/employees -H 'Content-type:application/json' -d '{"name": "Samwise Gamgee", "role": "gardener"}'
新しい作成しEmployee
たレコードを、そして私たちにコンテンツ背面を送信します。
{"id":3,"name":"Samwise Gamgee","role":"gardener"}
ユーザーを変更できます。
$ curl -X PUT localhost:8080/employees/3 -H 'Content-type:application/json' -d '{"name": "Samwise Gamgee", "role": "ring bearer"}'
ユーザーを更新:
{"id":3,"name":"Samwise Gamgee","role":"ring bearer"}
サービスの構成方法によっては、大きな影響が出る場合があります。この場合、更新は更新よりも置き換えの方が優れています。たとえば、名前が指定されていない場合は、それをクリアします。
削除できます...
$ curl -X DELETE localhost:8080/employees/3
$ curl localhost:8080/employees/3
Could not find employee 3
これらはすべて問題ありませんが、RESTfulによって提供されますか?(プロンプトが表示されない場合、答えはノーです。)
何が欠けていますか?