【问题标题】:How to get the data from ContainerRequestContext to build a DTO object如何从 ContainerRequestContext 获取数据以构建 DTO 对象
【发布时间】:2016-11-28 10:12:43
【问题描述】:

我是春季和球衣的新人。我正在尝试构建一个过滤器来检查请求是否具有正确的参数。这是我要检查的 json 部分:

"request":{
        "application":"1 Android Mobile",
        "version":1
    }

数据的元素是我的 VersionDTO 的一部分:

public class VersionDTO {
    int version;
    String application;

    public String getApplication() {
        return application;
    }

    public void setApplication(String application) {
        this.application = application;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

}

这是我的过滤器的代码:

    @Override
    public void filter(ContainerRequestContext requestContext) throws FilterException {

        if (isSecureURL(requestContext.getUriInfo().getPath())){}{
            try {

                versionFilterService.setVersionDTO(//here is where I want to pass the VersionDTO object with the data of the requestContext);
            } catch (ServiceException e) {
                    e.printStackTrace();
            }
        }
    }

    private boolean isSecureURL(String url) {
        return !UnSecureUrlEnum.isUnSecureUrl(url);
    }
}

我想做的是从 ContainerRequestContext 获取数据并构建一个 VersionDTO 以将对象传递给我的服务。这可能吗??

先谢谢了!

【问题讨论】:

    标签: spring-boot filter jersey


    【解决方案1】:

    是的,这是可能的。使用 Jersey,您可以在读取流之前对其进行缓冲,以便再次读取流。您需要转换到 Jersey ContainerRequest 在那里您可以 bufferEntity() 然后只需 readEntity 以获取反序列化的对象。

    @Override
    public void filter(ContainerRequestContext requestContext) throws FilterException {
    
        ContainerRequest cr = (ContanerRequest) requestContext;
        cr.bufferEntity();
        VersionDTO dto = cr.readEntity(VersionDTO.class);
    }
    

    【讨论】:

      【解决方案2】:

      无法在过滤器中获取实体,但是您会收到请求输入流,但您需要注意一些事情,因为只有一次可以流式传输。 看看这个,它可能对你有帮助.. How to use Jersey interceptors to get request body

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-18
        • 1970-01-01
        • 1970-01-01
        • 2021-10-28
        • 2014-03-09
        • 1970-01-01
        • 2016-05-01
        • 2016-05-27
        相关资源
        最近更新 更多