如何以编程方式使用球衣正确配置资源

How to correctly configure resources with jersey programmatically

我正在试用 Jersey Programmatic Resource Builder API 并且我能够 配置资源,但是当我得到一个空的 ContainerRequestContext 对象时 试图访问路径参数。可能是什么问题?

注意:我使用的是 2.35 版

public static void main(String[] args) {
    try {

        ResourceConfig config = new ResourceConfig();

        Resource.Builder resource = Resource.builder("/api/profile");
        Resource.Builder subresource = resource.addChildResource("{msisdn}/{source}");

        subresource.addMethod("GET")
                .produces(MediaType.TEXT_PLAIN_TYPE)
                .handledBy((ContainerRequestContext ctx) -> {
                    return Response.ok("Fetched Profile {" + (ctx == null) + "}").build();
                });

        subresource.addMethod("POST")
                .produces(MediaType.TEXT_PLAIN_TYPE)
                .handledBy((ContainerRequestContext ctx) -> {
                    return Response.ok("Posted Profile {" + (ctx == null) + "}").build();
                });

        config.registerResources(resource.build());

        Server server = new Server();

        ServerConnector connector = new ServerConnector(server);
        connector.setReuseAddress(true);
        connector.setName("Mambo Bad");
        connector.setHost("127.0.0.1");
        connector.setPort(Integer.parseInt("20000"));

    
        ServletContextHandler handler = new ServletContextHandler(server, "/", ServletContextHandler.NO_SESSIONS);
        handler.addServlet(new ServletHolder(new ServletContainer(config)), "/*");

      
        HandlerCollection handlers = new HandlerCollection();
        handler.setVirtualHosts(new String[]{"@" + connector.getName()});
        handlers.addHandler(handler);
        server.addConnector(connector);
        server.setHandler(handlers);

     
        server.start();
        server.join();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

问题出在您的 lambda 表达式上。 基本上,你有

Inflector<ContainerRequestContext, ?> lambda = (ContainerRequestContext ctx) -> {
                return Response.ok("Posted Profile {" + (ctx == null) + "}").build();
};

如果检查方法参数类型:

for (Method m : lambda.getClass().getMethods()) {
  if ("apply".equals(m.getName())) {
     for (Type t : m.getGenericParameterTypes()) {
         System.out.println(t); //java.lang.Object
     }
  }
}

你得到 java.lang.Object。因此 Jersey 尝试从实体流中获取 Object 类型并获取 null.

所以你需要告诉 java 使用真正匿名的 ContainerRequestContext 参数类型 class:

Inflector<ContainerRequestContext, Response> anonymous = new Inflector<>() {
    @Override
    public Response apply(ContainerRequestContext ctx) {
        return Response.ok("Posted Profile {" + (ctx == null) + "}").build();
    }
};

for (Method m : anonymous.getClass().getMethods()) {
    if ("apply".equals(m.getName())) {
        for (Type t : m.getGenericParameterTypes()) {
            System.out.println(t); // ContainerRequestContext 
        }
    }
}