Jersey:硬编码POST / PUT ObjectMapper,不需要Content-Type标头

时间:2016-08-19 23:26:19

标签: java json jersey jackson

我有一个Jersey 1.19.1资源,它实现了@PUT@POST方法。 @PUT方法需要JSON字符串作为输入/请求正文,而@POST方法则接受纯文本。 对于JSON映射,我使用的是Jackson 2.8。

由于资源定义为以这种方式工作,我不希望客户端需要指定Content-Type请求标头,因为Jersey需要它来确定要使用哪个ObjectMapper请求机构。

我想要的是告诉泽西岛“将此ObjectMapper用于此@PUT输入”,或“始终假设此输入将包含application/json Content-Type这种方法。“

@Produces(MediaType.APPLICATION_JSON)
@Path("/some/endpoint/{id}")
public class MyResource {

    @PUT
    public JsonResult put(
        @PathParam("id") String id,
        // this should always be deserialized by Jackson, regardless of the `Content-Type` request header.
        JsonInput input
    ) {
        log.trace("PUT {}, {}, {}", id, input.foo, input.bar);
        return new JsonResult("PUT result");
    }

    @POST
    public JsonResult post(
        @PathParam("id") String id,
        // this should always be treated as plain text, regardless of the `Content-Type` request header.
        String input
    ) {
        log.trace("POST {}, {}", id, input);
        return new JsonResult("POST result");
    }
}

我只找到this answer,但这不是我想要的,因为解决方案似乎应该要求客户端添加正确的Content-Type标头,否则请执行手动对象映射。

1 个答案:

答案 0 :(得分:0)

我设法找到了解决方法。我决定创建一个ObjectMapper,对应的ResourceFilter和一个注释类型,而不是声明在Jersey资源方法中使用哪个ResourceFilterFactory。每当使用此类型注释资源类或方法时,ResourceFilter都会将请求的Content-Type覆盖到注释参数中声明的任何内容。

这是我的代码:

OverrideInputType注释:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OverrideInputType {
    // What the Content-Type request header value should be replaced by
    String value();

    // which Content-Type request header values should not be replaced
    String[] except() default {};
}

OverrideInputTypeResourceFilter

public class OverrideInputTypeResourceFilter implements ResourceFilter, ContainerRequestFilter {
    private MediaType targetType;
    private Set<MediaType> exemptTypes;

    OverrideInputTypeResourceFilter(
        @Nonnull String targetType,
        @Nonnull String[] exemptTypes
    ) {
        this.targetType = MediaType.valueOf(targetType);
        this.exemptTypes = new HashSet<MediaType>(Lists.transform(
            Arrays.asList(exemptTypes),
            exemptType -> MediaType.valueOf(exemptType)
        ));
    }

    @Override
    public ContainerRequest filter(ContainerRequest request) {
        MediaType inputType = request.getMediaType();
        if (targetType.equals(inputType) || exemptTypes.contains(inputType)) {
            // unmodified
            return request;
        }

        MultivaluedMap<String, String> headers = request.getRequestHeaders();
        if (headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
            headers.putSingle(HttpHeaders.CONTENT_TYPE, targetType.toString());
            request.setHeaders((InBoundHeaders)headers);
        }
        return request;
    }

    @Override
    public final ContainerRequestFilter getRequestFilter() {
        return this;
    }

    @Override
    public final ContainerResponseFilter getResponseFilter() {
        // don't filter responses
        return null;
    }
}

OverrideInputTypeResourceFilterFactory

public class OverrideInputTypeResourceFilterFactory implements ResourceFilterFactory {

    @Override
    public List<ResourceFilter> create(AbstractMethod am) {
        // documented to only be AbstractSubResourceLocator, AbstractResourceMethod, or AbstractSubResourceMethod
        if (am instanceof AbstractSubResourceLocator) {
            // not actually invoked per request, nothing to do
            log.debug("Ignoring AbstractSubResourceLocator {}", am);
            return null;
        } else if (am instanceof AbstractResourceMethod) {
            OverrideInputType annotation = am.getAnnotation(OverrideInputType.class);
            if (annotation == null) {
                annotation = am.getResource().getAnnotation(OverrideInputType.class);
            }
            if (annotation != null) {
                return Lists.<ResourceFilter>newArrayList(
                    new OverrideInputTypeResourceFilter(annotation.value(), annotation.except()));
            }
        } else {
            log.warn("Got an unexpected instance of {}: {}", am.getClass().getName(), am);
        }
        return null;
    }

}

示例MyResource演示其用途:

@Produces(MediaType.APPLICATION_JSON)
@Path(/objects/{id}")
public class MyResource {
    @PUT
//  @Consumes(MediaType.APPLICATION_JSON)
    @OverrideInputType(MediaType.APPLICATION_JSON)
    public StatusResult put(@PathParam("id") int id, JsonObject obj) {
        log.trace("PUT {}", id);
        // do something with obj
        return new StatusResult(true);
    }

    @GET
    public JsonObject get(@PathParam("id") int id) {
        return new JsonObject(id);
    }
}

在泽西岛2中,您可以使用匹配后的ContainerRequestFilters

来执行此操作