泽西岛:@PathParam用逗号列表

问题描述 投票:8回答:1

我想用这种模式调用我的Web服务:

/resource/1,2,3

在我的类中,我想将我的参数绑定到对象列表

@Path("/resource")
public class AppWS {

    @GET
    @Path("/{params}")
    public Response get(@PathParam("params") List<MyObject> params) {
        return Response.status(200).entity("output").build();
    }
}

使用简单的对象:

public class MyObject {
    Integer value;
    public MyObject(Integer value) {
        this.value = value;
    }
}

nb:如果有可能我不想创建一个扩展List的MyObjectList(并且有一个构造函数可以拆分我的字符串)

我该怎么办?

java jersey jax-rs jersey-2.0 path-parameter
1个回答
6
投票

我不确定1,2,3的方式。

如果你坚持,

private Response get(List<MyObject> params) {
}

@GET
@Path("/{params}")
public Response get(@PathParam("params") String params) {

    return get(Stream.of(params.split(","))
        .map(MyObject::new)
        .collect(Collectors.toList()));
}

如果你真的坚持,

注解,

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface MyObjectsParam {

}

转换器,

public class MyObjectsParamDateConverter
    implements ParamConverter<List<MyObject>> {

    @Override
    public List<MyObject> fromString(final String value) {
        return Stream.of(params.split(","))
          .map(MyObject::new)
          .collect(Collectors.toList())
    }

    @Override
    public String toString(final List<MyObject> value) {
        return value.stream()
            .map(o -> o.getValue())
            .map(Object::toString)
            .collect(Collectors.joining(","));
    }
}

供应商,

@Provider
public class MyObjectsParamConverterProvider
    implements ParamConverterProvider {

    @Override
    @SuppressWarnings("unchecked")
    default ParamConverter getConverter(final Class<S> rawType,
                                        final Type genericType,
                                        final Annotation[] annotations) {
        for (final Annotation annotation : annotations) {
            if (MyObjectsParam.class.isInstance(annotation)) {
                return new MyObjectsParamDateConverter();
            }
        }

        return null;
    }
}

现在你可以像这样使用它。

@GET
@Path("/{params}") // still '1,2,3'
public Response get(
    @PathParam("params")
    @MyObjectsParam // IN ACTION!!!
    List<MyObject> params) {

}
© www.soinside.com 2019 - 2024. All rights reserved.