春季启动:将数据发送到一个端点,但对其他端点隐藏

huangapple go评论59阅读模式
英文:

spring boot: sending data to 1 endpoint but hiding from other

问题

我有一个简单的Spring Boot应用程序,我的模型包含3个字段。控制器暴露了2个端点/e1和/e2。我想实现的目标是,当调用/e1时,我希望返回模型中的所有3个字段,但当调用/e2时,我希望只返回2个字段,并将第3个字段从中隐藏。

有没有方法可以做到这一点,应该如何实现?谢谢。

英文:

I have a simple spring boot application, my model contains 3 fields. and controller exposes 2 endpoints /e1 and /e2. what I want to achieve is that when /e1 is called I want to return all 3 fields from my model by when /e2 is called I was to return just 2 fields and hiding the 3rd field from it.

is there a way to do it and how this can be done ? thanks

答案1

得分: 0

首先,您应该始终拥有2个类 - 实体和其DTO表示 - 即使它们的字段非常相似。这给您带来了以下好处:

  • 与外部消费者的独立性,您可以在将来更改模型,但契约保持不变
  • 利用Hibernate延迟加载的优势的机会
  • 轻松解决您的问题:只需有2个DTO,一个带有所有字段,另一个不带隐藏字段。

您可能需要bean映射器来将实体转换为DTO。

英文:

First, you should always have 2 classes - entity and its dto presentation - even if they fields are very similar. This gives you:

  • independcy from external consumers, you may change your model in future but the contract remains the same
  • opportunity to use advantages of Hiberante laze loading
  • easily solve your issue: just have 2 DTOs, one with all fields, other one without hidden field.

You might need bean mapper for converting entity to DTO.

答案2

得分: 0

两种解决方案,您可以尝试其中之一:

  1. 创建两个POJO类,一个带有3个字段,另一个带有2个字段,并根据需要返回。
  2. 如果您不想要单独的POJO类,那么可以在一个POJO中设置所有3个字段的值,当调用/e2时,遍历它并显式地清除您想要隐藏的值。
英文:

Two solutions you can try either of them ..

  1. Create two POJO's One with 3 field and another with 2 fields and return accordingly.
  2. If you dont want separate pojo then set value of all 3 fields in pojo and when /e2 called, iterate over it and explicitely blank out that value which you want hide.

huangapple
  • 本文由 发表于 2020年10月23日 19:16:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64498960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定