如何以编程方式正确配置Jersey资源

2022-03-01 00:00:00 java jax-rs jersey embedded-jetty
我正在试用Jersey Programmal 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参数类型:

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 
        }
    }
}

相关文章