【问题标题】:RestTemplate not carrying request attributesRestTemplate 不携带请求属性
【发布时间】:2019-09-17 23:28:50
【问题描述】:

我有 2 个服务,例如 Parent 和 Child。 在父服务中,有

request.setAttribute("key","someValue");

从父服务调用了子服务的端点之一。

restTemplate.exchange(url, HttpMethod.GET, null, Object.class);

在 Child RestController 中,我期望在 Parent 中设置属性(键)。

request.getAttribute("key") --> returns null

但是我得到了空值,你能建议我做错了什么吗?我期待 Parent 的相同请求对象将传递给 Child。但我的理解似乎是错误的。请纠正我。

谢谢。

【问题讨论】:

    标签: spring spring-boot spring-mvc resttemplate spring-restcontroller


    【解决方案1】:

    我不确定您要完成什么,但您似乎正在尝试在您的 HttpServletRequest 中设置一个属性,并希望将该属性返回到您的端点。

    request 对象是由 Web 容器创建的,但它并没有像您认为的那样'转移' 到您的 Child 端点。该对象仅存在于处理请求的端点上,直到发回响应。

    如果您需要将参数传递给您的子端点,您需要将其作为查询参数添加到 url,例如:

    url += "?key=someValue"
    

    或者如果它是一个更复杂的对象,您应该使用 GET 以外的其他 HTTP 方法并将其添加为您的请求正文。然后您应该在 Child 端点中收到参数。

    您可以在这里查看几个示例:

    https://springbootdev.com/2017/11/21/spring-resttemplate-exchange-method/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2016-06-20
      相关资源
      最近更新 更多