考虑到使用Spring Boot框架开发的RESTful Web服务,我想要一种抑制响应中所有用户的birthDate
的方法。这是我在寻找解决方案后实现的方法:
@RestController
public class UserResource {
@Autowired
private UserDAOservice userDAOService;
@GetMapping("/users")
public MappingJacksonValue users() {
List<User> users = userDAOService.findAll();
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter
.filterOutAllExcept("id", "name");
FilterProvider filters = new SimpleFilterProvider().addFilter(
"UserBirthDateFilter", filter);
MappingJacksonValue mapping = new MappingJacksonValue(users);
mapping.setFilters(filters);
return mapping;
}
}
但是,当我在浏览器中单击其余端点时,仍然可以在响应中看到用户的出生日期:
{
"id": 1,
"name": "Adam",
"birthDate": "1980-03-31T16:56:28.926+0000"
}
问题1:我可以使用什么API来实现我的目标?
接下来,假设我想结合过滤坚持使用HATEOAS,我该怎么做。我无法弄清楚可以一起使用这两个功能的API:
@GetMapping("/users/{id}")
public EntityModel<User> users(@PathVariable Integer id) {
User user = userDAOService.findById(id);
if (user == null) {
throw new ResourceNotFoundException("id-" + id);
}
EntityModel<User> model = new EntityModel<>(user);
WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).users());
model.add(linkTo.withRel("all-users"));
//how do I combine EntityModel with filtering?
return model;
}
问题2:如何将EntityModel
与MappingJacksonValue
合并?
有一个更简单的方法,在您的传输对象(要发送回客户端的类)上,您可以简单地使用@JsonIgnore批注以确保该字段未序列化,并因此发送给客户端。因此,只需在您的生日类的User类中添加@JsonIgnore。
您还可以在此处阅读有关此方法的更多信息:
https://www.baeldung.com/jackson-ignore-properties-on-serialization