【问题标题】:Setting Uri dynamically in HTTP Location Header在 HTTP 位置标头中动态设置 Uri
【发布时间】:2017-01-03 14:07:20
【问题描述】:

我实现了一个创建 Employee 的 Rest 服务。在响应消息中,我想使用新创建的 Employee 资源 Uri 动态设置 HTTP Location 标头。

下面的代码运行良好,我可以按预期看到 Location 标头中的值。但是我在 EmpService 中硬编码了 Uri,我希望它是动态的。如何提取/传递 Uri 信息到 EmpService bean?

Config.xml


 <int-http:inbound-gateway
     request-channel="httpPostChannel"
     reply-channel="responseChannel"
     path="/emp"
     supported-methods="POST"   
     message-converters="converters" 
     request-payload-type="com.samples.jaxb.Employee"/>

<int:service-activator ref="empService" method="post"   
                       input-channel="httpPostChannel"   output-channel="responseChannel"/>

EmpService.java

public Message<Employee> post (Message<Employee> msg) {

    Employee emp = empDao.createEmployee(msg.getPayload());
    return MessageBuilder.withPayload(emp)
                         .setHeader(org.springframework.http.HttpHeaders.LOCATION,  "http://localhost:8080/RestSample/emp/" + emp.getEmpId())
                         .build();
}                          

【问题讨论】:

    标签: spring-integration


    【解决方案1】:

    实际上即使现在你的 URI 也是动态的:

    "http://localhost:8080/RestSample/emp/" + emp.getEmpId()

    OTOH,您始终可以在应用程序从某些外部属性启动期间通过 setter 或 @Value 属性注入它。

    或者您甚至可以从传入的Message 中提取一些属性/标题。

    但是我猜你想知道你运行的主机和端口。

    您可以通过InetAddress.getLocalHost() 了解host

    您可以通过适当的 ServletContainer 供应商 API 提取 port,例如对于 Tomcat:Get the server port number from tomcat with out a request.

    使用 Spring Boot,您可以使用 @LocalServerPort:

    * Annotation at the field or method/constructor parameter level that injects the HTTP
    * port that got allocated at runtime. Provides a convenient alternative for
    * <code>&#064;Value(&quot;${local.server.port}&quot;)</code>.
    

    虽然...我想这个应该足够了:

    .setHeader(org.springframework.integration.http.HttpHeaders.REQUEST_URL,
                            request.getURI().toString())
    

    我的意思是您在&lt;int-http:inbound-gateway&gt; 之后传入的Message 已设置标题。在我使用 Spring Boot 和随机 Tomcat 端口的测试用例中,它看起来像:

    "http_requestUrl" -> "http://localhost:64476/service/?name=foo"
    

    【讨论】:

    • 我可以从你提到的标题中获取完整的 Url。我实际上正在寻找任何开箱即用的选项来获取 Uri 直到上下文路径。 'localhost:8080/RestSample'
    • ??? “直到上下文路径”对我来说完全等于http://localhost:8080。仅仅因为/RestSample 是一个上下文。您可以完全从URI 对象中获取所有这些部分(方案、主机、端口)。请在您的示例中展示您希望动态构建的部分。
    • 好的。怎么了?只需在您的代码中执行此操作!我还是不明白你想从我们这里得到什么。您有标题、要解析的 URI 类、UriComponentsBuilder 以及 Spring 和 Commons Http Client 中的其他一些 UriUtils。另一方面,我们总是可以通过代码 Java 能力做到这一点!
    • 太棒了!这是否意味着我们可以将问题视为已关闭?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    相关资源
    最近更新 更多