有没有办法让查询参数“x”包含在URL中,如果省略它,默认值,因为目前我需要做的是下面的内容,我必须为每个参数做一个默认值;有一个更好的方法吗?我使用泽西岛版本1.12
public Response getResponse(@DefaultValue("test") @QueryParam("x") String x)
UriBuilder uriBuilder = UriBuilder.fromUri(uriInfo.getRequestUri());
uriBuilder = uriBuilder.replaceQueryParam(x);
QueryContext.setUrl(uriBuilder.build().toString());
谢谢
答案 0 :(得分:0)
我不知道采用标准的Jersey方法,但你可以用AOP拦截这个方法并执行以下操作:
public class UpdateQueryParamInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation method) throws Throwable {
UriBuilder builder = null;
for (Object arg: method.getArguments()) {
if (arg instanceof UriInfo) {
UriInfo info = (UriInfo)arg;
builder = UriBuilder.fromUri(info.getRequestUri());
}
}
Annotation[][] annotations = method.getMethod().getParameterAnnotations();
for (int i = 0; i < method.getArguments().length; i++) {
if (annotations[i].length > 0) {
DefaultValue def = null;
QueryParam param = null;
for (Annotation annotation: annotations[i]) {
if (annotation instanceof DefaultValue) {
def = (DefaultValue)annotation;
} else if (annotation instanceof QueryParam) {
param = (QueryParam)annotation;
}
}
if ((null != def) && (null != param)) {
builder = builder.replaceQueryParam(param.value(), method.getArguments()[i]);
}
}
}
//Do something with builder.build().toString());
return method.proceed();
}
}
我不确定你的代码中是什么QueryContext
类 - 但你也可以在方法中找到并在拦截器中执行setUrl
方法...