【问题标题】:Jersey 2 - get base URI on ClientJersey 2 - 获取客户端的基本 URI
【发布时间】:2016-08-21 19:27:59
【问题描述】:

我需要将UriInfo 注入客户端,但找不到解决方案。 主要目标是在创建 WebTarget 时获取基本 URI (localhost:port)。事实上,应用程序被不同的 Web 客户端使用,并且需要显式 URI。此外,我想测试客户端资源通信,因此我也需要在我的测试类中获得严格的 URI。 应用程序是多模块 Maven 项目。资源和客户端位于不同的模块中。
为了清楚起见,我在下面描述了项目结构(请不要注意文件夹结构 - 它以简单的形式描述):

--service-module
       \Resource.java
       \web.xml
--client-module
       \Client.java
--client-test-module
       \ClientResourceIntegrationTest.java

Client.java

public class Client {

    @Context
    UriInfo uriInfo;

    public Result getResult(String userName, Filter queryFilter) {
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.register(Filter.class);
        Client client = ClientBuilder.newClient(clientConfig);

        WebTarget webTarget = client
                //need to change on dynamically retrieved URI
                .target("http://localhost:1234/")
                .path("all/")
                .path(userName);

        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
        Response response = invocationBuilder.post(Entity.entity(queryFilter, MediaType.APPLICATION_JSON));
        int responseStatus = response.getStatus();
        Result queryResult = response.readEntity(Result.class);
        response.close();
        return queryResult;
    }

}

Resource.java

@Path("/")
public class Resource {

    @Context
    UriInfo uriInfo;

    @POST
    @Path("all/{user}")
    @Produces(MediaType.APPLICATION_JSON)
    public Result getAll(@PathParam("user") String userName, Filter filter) {
        List<Map<String, Object>> attributes = new ArrayList<Map<String, Object>>();
        Map<String, Object> values = new HashMap<String, Object>();
        values.put("value", 1);
        attributes.add(values);

        Result result = new Result(attributes);
        return result;
    }

}

Jersey 的 ServletContainer 定义在 web.xml 中,位于 service-module 中。扫描的包只是位于该模块中的资源(因此UriInfo 被注入到资源对象中)。其余类的实例(包括客户端)是在没有 IoC 容器的情况下创建的(显然UriInfo 为空)。所以,我不知道在这种情况下如何获取 URI。如果您对在哪里阅读或什至如何阅读有任何建议 - 请发表评论。

【问题讨论】:

    标签: java jersey-2.0 jersey-client


    【解决方案1】:

    我不确定我是否理解您的问题。部署 Web 应用程序时,您可以在 EAR 文件中定义上下文根。如果您在不同的应用程序服务器上安装相同的 EAR,则该上下文根不会改变,除非部署者配置不同的上下文根。

    客户端可能会在不同的机器上运行,因此您需要找到一种方法来配置客户端,其中包含在哪里可以找到服务器的信息。这通常由数据库中的属性文件或配置表完成。只需为所有合适的环境设置配置文件并将它们提供给客户端。

    【讨论】:

    • 感谢您的回复。我不确定它是否适合。我决定使用 Jersey 的 DI 来访问上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多