SpringのRequestBodyおよびResponseBodyアノテーション
1. 前書き
この簡単な記事では、Springの@RequestBodyおよび@ResponseBodyアノテーションの簡潔な概要を説明します。
参考文献:
Spring @Controllerおよび@RestControllerアノテーション
Spring MVCの@Controllerアノテーションと@RestControllerアノテーションの違いについて学びます。
2. @RequestBody
簡単に言うと、@RequestBodyアノテーションは、HttpRequest本体を転送オブジェクトまたはドメインオブジェクトにマップし、インバウンドHttpRequest本体のJavaオブジェクトへの自動逆シリアル化を可能にします。
まず、Springコントローラーのメソッドを見てみましょう。
@PostMapping("/request")
public ResponseEntity postController(
@RequestBody LoginForm loginForm) {
exampleService.fakeAuthenticate(loginForm);
return ResponseEntity.ok(HttpStatus.OK);
}
Springは適切なJSONタイプが指定されていると仮定して、JSONをJavaタイプに自動的にデシリアライズします。 デフォルトでは、@RequestBodyアノテーションでアノテーションを付けるタイプは、クライアント側コントローラーから送信されるJSONに対応している必要があります。
public class LoginForm {
private String username;
private String password;
// ...
}
ここで、HttpRequest本体を表すために使用するオブジェクトは、LoginFormオブジェクトにマップされます。
CURLを使用してこれをテストしましょう:
curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data
'{"username": "johnny", "password": "password"}' "https://localhost:8080/.../request"
これが、Spring REST APIと@RequestBodyアノテーションを使用するAngularクライアントに必要なすべてです!
3. @ResponseBody
@ResponseBodyアノテーションは、返されたオブジェクトが自動的にJSONにシリアル化され、HttpResponseオブジェクトに戻されることをコントローラーに通知します。
カスタムResponseオブジェクトがあるとします。
public class ResponseTransfer {
private String text;
// standard getters/setters
}
次に、関連するコントローラーを実装できます。
@Controller
@RequestMapping("/post")
public class ExamplePostController {
@Autowired
ExampleService exampleService;
@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(
@RequestBody LoginForm loginForm) {
return new ResponseTransfer("Thanks For Posting!!!");
}
}
ブラウザの開発者コンソールまたはPostmanなどのツールを使用すると、次の応答が表示されます。
{"text":"Thanks For Posting!!!"}
ここではデフォルトで実行されるため、Remember, we don’t need to annotate the @RestController-annotated controllers with the @ResponseBody annotation。
4. 結論
@RestControllerおよび@ResponseBodyアノテーションの使用方法を示すSpringアプリ用のシンプルなAngularクライアントを構築しました。
いつものように、コードサンプルはover on GitHubで利用できます。