Gui*_*ume 8 java jax-rs jersey path-parameter jersey-2.0
我想用这种模式调用我的Webservice:
/resource/1,2,3
Run Code Online (Sandbox Code Playgroud)
在我的类中,我想将我的参数绑定到对象列表
@Path("/resource")
public class AppWS {
@GET
@Path("/{params}")
public Response get(@PathParam("params") List<MyObject> params) {
return Response.status(200).entity("output").build();
}
}
Run Code Online (Sandbox Code Playgroud)
使用简单的对象:
public class MyObject {
Integer value;
public MyObject(Integer value) {
this.value = value;
}
}
Run Code Online (Sandbox Code Playgroud)
nb:如果有可能我不想创建一个扩展List的MyObjectList(并且有一个分割我的字符串的构造函数)
我该怎么办?
我不确定的方式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()));
}
Run Code Online (Sandbox Code Playgroud)
如果你真的坚持,
注解,
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface MyObjectsParam {
}
Run Code Online (Sandbox Code Playgroud)
转换器,
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(","));
}
}
Run Code Online (Sandbox Code Playgroud)
供应商,
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以像这样使用它.
@GET
@Path("/{params}") // still '1,2,3'
public Response get(
@PathParam("params")
@MyObjectsParam // IN ACTION!!!
List<MyObject> params) {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3269 次 |
| 最近记录: |