简体   繁体   English

从RESTful Web服务发送JSON时是否需要DTO?

[英]Are DTO's necessary when sending JSON from a RESTful web service?

I'm attempting to build a RESTful web service using Spring MVC. 我正在尝试使用Spring MVC构建RESTful Web服务。 I'm using Jackson's fasterxml JSON parser for communication between the client and server side. 我正在使用Jackson的fastxml JSON解析器进行客户端和服务器端之间的通信。

I'm trying to determine whether or not to implement DTO's (Data Transfer Objects) into my RESTful API. 我正在尝试确定是否在我的RESTful API中实现DTO(数据传输对象)。 I'm currently utilizing Jackson's @JsonProperty(access = Access.WRITE_ONLY) and @JsonIgnore annotations to prevent sensitive fields (such as passwords) from being sent to the client side. 我目前正在使用Jackson的@JsonProperty(access = Access.WRITE_ONLY)@JsonIgnore批注来防止敏感字段(例如密码)发送到客户端。

So, are DTO's necessary when using JSON for communication between the client and the server when omitting sensitive fields from the response body or are the annotations @JsonIgnore and @JsonProperty sufficient enough to prevent sensitive data leakage? 因此,从响应正文中@JsonIgnore敏感字段时,使用JSON在客户端和服务器之间进行通信时是否需要DTO?或者注解@JsonIgnore@JsonProperty足以防止敏感数据泄漏?

Assuming you talk about serializing entities to json instead of using DTOs which is not very clear, yes DTOs would be the proper choice from an architectural point of view. 假设您谈论的是将实体序列化为json而不是使用DTO(不清楚),那么从架构的角度来看,DTO是正确的选择。 Underneath controllers there most commonly is the service layer which functions on some domain, let's say persistence entities or entities coming from a queuing system. 在控制器下,最常见的是服务层,该服务层在某个域上起作用,比如说持久性实体或来自排队系统的实体。

It is sane to isolate your REST API from your domain and map lower level domain entities to DTOs at service level, most commonly using a POJO mapper. 将REST API与您的域隔离并在服务级别上将较低级别的域实体映射到DTO是最明智的选择,最常见的方法是使用POJO映射器。

This would have some performance impact which you can optimize but has the benefit of structural isolation between layers. 这将对性能产生一些影响,您可以对其进行优化,但具有层之间结构隔离的优势。

The second benefit is that you can aggregate information from lower layers and manipulate your REST interface as serves you best, 第二个好处是您可以汇总来自较低层的信息,并以最佳方式操作REST接口,

If again we talk about entities it's wrong to add REST api attributes in persistence layer. 如果我们再次谈论实体,那么在持久层中添加REST api属性是错误的。

All this from a conceptual point of view. 从概念的角度来看所有这些。 Another thing that should prevent you from serving entities of JPA2 is that the objects returned from queries are enhanced objects so using a mapper will again give you more control. 阻止您提供JPA2实体的另一件事是,查询返回的对象是增强对象,因此使用映射器将再次为您提供更多控制权。

Choosing the mapper configuration is a bit tricky though since if you expose crud operations as in the persistence/domain level mapping becomes redundant. 选择映射器配置有些棘手,因为如果您在持久性/域级别公开裸操作,则映射将变得多余。 Exposing entities will only cause scaling problems 暴露实体只会引起缩放问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM