java - MessageBodyReaders 如何使用

标签 java rest servlets jersey-2.0 dropwizard

给定类似的内容:

例如

class User{
  String name;
  String someField1;
}

 @Consumes("some/media-type")
class ResourceA{

    public Response test(@FormParam("u") User u, @FormParam("f) String someField){
    }
}

几个问题:

  1. 是否会使用单个 MessageBodyReader 来反序列化 User,或者 user 中的每个字段是否会由不同的读取器反序列化?
  2. 任何/所有这些都需要 @context 吗?
  3. User 类中的字段是否需要 @FormParam

我试图了解服务器是否会获取可用的读取器列表,并且对于测试中的每个参数,检查是否有任何读取器可以反序列化该类型。或者,如果第一个与所使用的媒体类型匹配的读取器预计会反序列化所有参数。

如果服务器正在迭代每个参数,并且为每个参数找到最合适的读取器,则传递给 readFrom 的输入流是相同的实例,并且每个读取器都是有道理的。通过输入流前进。是这种情况还是我完全误解了 MessageBodyReader 的用途?

最佳答案

查看此文档,了解如何 entity providers are selected 。特别是:

Procedure 7.2. MessageBodyReader Selection Algorithm

  1. Obtain the media type of the request. If the request does not contain a Content-Type header then use application/octet-stream media type.

  2. Identify the Java type of the parameter whose value will be mapped from the entity body. The Java type on the server is the type of the entity parameter of the resource method. On the client it is the Class passed to readFrom method.

  3. Select the set of available MessageBodyReader providers that support the media type of the request.

  4. Iterate through the selected MessageBodyReader classes and, utilizing their isReadable method, choose the first MessageBodyReader provider that supports the desired combination of Java type/media type/annotations parameters.

If Step 4 locates a suitable MessageBodyReader, then use its readFrom method to map the entity body to the desired Java type.

Otherwise, the server runtime MUST generate a NotSupportedException (HTTP 415 status code) and no entity and the client runtime MUST generate an instance of ProcessingException.

@Context 不是必需的,@FormParam 也不需要添加到您的 bean 中 - 只需添加到 REST 资源方法即可。

关于java - MessageBodyReaders 如何使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23841203/

相关文章:

java - 设置由 Activity 链接的新页面

asp.net - REST 服务的成员资格/授权

python - 使用rest api从python应用程序创建Moodle用户

java - jQuery js 文件未加载

java - 在 Java Servlet 上打印请求调试信息

java - 使用 apache 数学获取分数的百分位数

java - 比 Sprite/BufferedImage 更有效的东西。

java - 在此特定示例中如何使用模数递减?

java - 无法在 apache-camel 中创建路由

tomcat - 如何在运行时在 servlet 和 tomcat 中添加子域?