如何将我的注册提供商与动态创建的球衣资源类一起使用?

时间:2019-02-08 14:33:11

标签: java jersey jax-rs

我只想知道我们如何将注册的提供程序(MessageBodyReader和MessageBodyWriter)与动态创建的球衣资源类(即通过程序化球衣资源api通过编程方式创建的球衣资源)一起使用

 Resource.Builder resourceBuilder = Resource.builder();
        resourceBuilder.path("helloworld/{name}");

        ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("POST");
        methodBuilder.produces(MediaType.TEXT_PLAIN_TYPE).consumes(MediaType.TEXT_PLAIN_TYPE)
                .handledBy(new MyInflector());
         Resource resource = resourceBuilder.build();
        registerResources(resource);

现在如何在MyInflector类中使用我注册的MessageBodyReader和Writer,如下所示

public class MyInflector implements Inflector<ContainerRequestContext, String>{

    @Override
    public String apply(ContainerRequestContext arg0) {
        System.out.println("Processing request");
         MultivaluedMap<String, String> pParams =arg0.getUriInfo().getPathParameters();
         InputStream stream=arg0.getEntityStream();
         if (stream != null) {
                Writer writer = new StringWriter();

                char[] buffer = new char[5120];
                try {
                    Reader reader = new BufferedReader(
                            new InputStreamReader(stream, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                return writer.toString();
            } else {
                return "";
            }
    }

}

1 个答案:

答案 0 :(得分:1)

您可以执行的操作是将ContainerRequestContext强制转换为ContainerRequest(这是ContainerRequestContext接口的Jersey实现。使用此类,您可以调用containerRequest.readEntity(Pojo.class)。会导致Pojo.class类的阅读器被调用(假设内容类型也与端点消耗的媒体类型匹配)。

@Override
public String apply(ContainerRequestContext requestContext) {
    ContainerRequest containerRequest = (ContainerRequest)requestContext;
    Model model = containerRequest.readEntity(Model.class);
    ...
}