【问题标题】:Append Object property to RestEasy InputStream containerRequestContext将 Object 属性附加到 RestEasy InputStream containerRequestContext
【发布时间】:2020-10-07 23:15:41
【问题描述】:

我正在尝试将主体 ID 作为正文的一部分添加到每个传入请求中。这是我正在使用的代码:

        InputStream in = containerRequestContext.getEntityStream();
        String jsonRequestString = IOUtils.toString(in, encoding);

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser parser = factory.createParser(jsonRequestString);
        JsonNode jsonNode = mapper.readTree(parser);

        ((ObjectNode) jsonNode).put(PRINCIPAL_ID, containerRequestContext.getSecurityContext().getUserPrincipal().getName());

        containerRequestContext
                .setEntityStream(IOUtils.toInputStream(mapper.writeValueAsString(jsonNode), encoding));

这是我的资源:

@POST
@Path("/service")
@RolesAllowed(USER_ROLE)
@Produces(MediaType.APPLICATION_JSON)
public Response myService(String principalId, String input){
    // do stuff
}

当请求命中资源时,我可以看到新的 json 字符串绑定在 principalId 参数上,例如

principalId = {"principalId": "id", "input":"input"}

有没有办法将每个属性绑定到各自的参数?

【问题讨论】:

    标签: java spring-boot resteasy


    【解决方案1】:

    你有两个选择:

    • 编写拦截器(例如,使用 AspectJ)处理所有端点并将principalId 填充到方法的参数或 POJO。
    • 写一个servlet filter。此选项需要读取两次相同的请求。第一次读取将在过滤器中进行,并进行以下预处理,第二次读取将在 Spring servlet 中进行。

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2013-06-30
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多