1.@JsonView注解
* 使用接口声明多个视图* 在值对象的get方法上指定视图* 在controller方法上指定视图
public class User { @JsonView(UserSimpleView.class) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }//在get方法上使用接口@JsonView(UserDetailView.class) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @JsonView(UserSimpleView.class) public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } private Date birthday; private String id; private String username;//notblank注解声明密码不可为空 @NotBlank private String password;//声明视图接口 public interface UserSimpleView{}; public interface UserDetailView extends UserSimpleView{};}
@PostMapping//在controller上使用注解//返回简单视图,即只返回username和id,在WEB开发中,通常不返回密码,安全性考虑@JsonView(User.UserSimpleView.class)//使用Valid注解,校验User对象中的notblank,BindingResult可以拿到和处理错误信息,否则无法进入方法体,不能输出有效的错误提示public User creat(@Valid @RequestBody User user, BindingResult errors){ //@RequestBody映射请求体到java方法参数 if(errors.hasErrors()){ System.out.println("密码不可为空"); System.out.println(errors.getAllErrors().toString()); } System.out.println(user.getUsername()); System.out.println(user.getPassword()); System.out.println(user.getId()); System.out.println(user.getBirthday()); user.setId("1"); return user;}