【问题标题】:Jersey: @PathParam with commas to List<MyObject>泽西岛:@PathParam 用逗号表示 List<MyObject>
【发布时间】:2015-01-23 21:27:38
【问题描述】:

我想用这种模式调用我的 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(并且有一个拆分我的字符串的构造函数)

我该如何继续?

【问题讨论】:

  • 您的链接已损坏。你能直接说出模式的名称或解释一下吗?
  • 您好 gla3dr,谢谢您的回复。这不是一个真正的链接,它只是一个可以访问资源的 uri 示例。事实上,我想在路径中使用逗号来表示多个值(我编辑我的帖子)
  • 哦,我明白了。我误解了你的意思,我的错!你现在拥有它的方式更加清晰。
  • 不!是我。我已经澄清了我的帖子
  • 嗨。它真的必须是/resource/1,2,3。难道不是resource?1,2,3之类的吗? QueryParam 明确接受不止一个参数,尽管您不会那样写(它通常类似于resource?id=1,id=2,id=3)。希望对您有所帮助。

标签: java jersey jax-rs jersey-2.0 path-parameter


【解决方案1】:

我不确定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) {

}

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2015-09-07
    • 2014-09-28
    相关资源
    最近更新 更多