日常提交

This commit is contained in:
wu xiangkai
2022-12-01 15:19:38 +08:00
parent 632324d94b
commit 0f6c62e459

View File

@@ -393,6 +393,72 @@ public void handle(HttpEntity<Account> 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<String> 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