日常提交
This commit is contained in:
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user