From 0f6c62e4595d48b19d2cf67537d1af4e363d8ba7 Mon Sep 17 00:00:00 2001 From: wu xiangkai Date: Thu, 1 Dec 2022 15:19:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A5=E5=B8=B8=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spring/Spring core/SpringMVC.md | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/spring/Spring core/SpringMVC.md b/spring/Spring core/SpringMVC.md index c06042c..5a63206 100644 --- a/spring/Spring core/SpringMVC.md +++ b/spring/Spring core/SpringMVC.md @@ -393,6 +393,72 @@ public void handle(HttpEntity entity) { // ... } ``` +#### @ResponseBody +通过使用@ResponseBody注解,可以将handler method的返回值序列化到响应体中,通过HttpMessageConverter。具体使用如下所示: +```java +@GetMapping("/accounts/{id}") +@ResponseBody +public Account handle() { + // ... +} +``` +同样的,@ResponseBody注解也支持class-level级别的使用,在使用@ResponseBody标注类后对所有controller method都会起作用。 +通过@RestController可以起到同样作用。 +#### ResponseEntity +ResponseEntity使用和@ResponseBody类似,但是含有status和headers。ResponseEntity使用如下所示: +```java +@GetMapping("/something") +public ResponseEntity handle() { + String body = ... ; + String etag = ... ; + return ResponseEntity.ok().eTag(etag).body(body); +} +``` +#### Jackson JSON +Spring MVC为Jackson序列化view提供了内置的支持,可以渲染对象中的字段子集。 +如果想要在序列化返回值时仅仅序列化某些字段,可以通过@JsonView注解来指明序列化哪些字段。 +##### @JsonView +@JsonView的使用如下所示, +- 通过interface来指定渲染的视图 +- 在字段的getter方法上通过@JsonView来标注视图类名 +- interface支持继承,如WithPasswordView继承WithoutPasswordView,故而WithPasswordView在序列化时不仅会包含其自身的password字段,还会包含从WithoutPasswordView中继承而来的name字段 +> 对于一个handler method,只能够通过@JsonView指定view class,如果想要激活多个视图,可以使用合成的view class +```java +@RestController +public class UserController { + @GetMapping("/user") + @JsonView(User.WithoutPasswordView.class) + public User getUser() { + return new User("eric", "7!jd#h23"); + } +} +public class User { + public interface WithoutPasswordView {}; + public interface WithPasswordView extends WithoutPasswordView {}; + + private String username; + private String password; + + public User() { + } + + public User(String username, String password) { + this.username = username; + this.password = password; + } + + @JsonView(WithoutPasswordView.class) + public String getUsername() { + return this.username; + } + + @JsonView(WithPasswordView.class) + public String getPassword() { + return this.password; + } +} +``` +### Model