我正在编写一个 REST API,使用 RestEasy 2.3.4.Final。 我知道拦截器将拦截我的所有请求,并且 PreProcessInterceptor 将是第一个(在一切之前)被调用的。我想知道如何让这个拦截器在特定方法被调用时被调用。
我尝试同时使用 PreProcessInterceptor 和 AcceptedByMethod,但无法读取我需要的参数。 例如,我只需要在调用此方法时运行我的拦截器:
@GET
@Produces("application/json;charset=UTF8")
@Interceptors(MyInterceptor.class)
public List<City> listByName(@QueryParam("name") String name) {...}
更具体地说,我需要在所有具有 @QueryParam("name")
在它的签名上,这样我就可以捕获这个名字并在一切之前做点什么。
这可能吗?我试图在拦截器中捕获“名称”参数,但我无法做到这一点。
有人能帮帮我吗?
最佳答案
您可以按照 RESTEasy documentation 中的说明使用 AcceptedByMethod
创建一个同时实现 PreProcessInterceptor
和 AcceptedByMethod
的类。在 accept
方法中,您可以检查该方法是否有一个用 @QueryParam("name")
注释的参数。如果该方法具有该注释,则从 accept
方法返回 true。
在preProcess
方法中,您可以从request.getUri().getQueryParameters().getFirst("name")
获取查询参数。
编辑:
这是一个例子:
public class InterceptorTest {
@Path("/")
public static class MyService {
@GET
public String listByName(@QueryParam("name") String name){
return "not-intercepted-" + name;
}
}
public static class MyInterceptor implements PreProcessInterceptor, AcceptedByMethod {
@Override
public boolean accept(Class declaring, Method method) {
for (Annotation[] annotations : method.getParameterAnnotations()) {
for (Annotation annotation : annotations) {
if(annotation.annotationType() == QueryParam.class){
QueryParam queryParam = (QueryParam) annotation;
return queryParam.value().equals("name");
}
}
}
return false;
}
@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
String responseText = "intercepted-" + request.getUri().getQueryParameters().getFirst("name");
return new ServerResponse(responseText, 200, new Headers<Object>());
}
}
@Test
public void test() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getProviderFactory().getServerPreProcessInterceptorRegistry().register(new MyInterceptor());
dispatcher.getRegistry().addSingletonResource(new MyService());
MockHttpRequest request = MockHttpRequest.get("/?name=xxx");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals("intercepted-xxx", response.getContentAsString());
}
}
关于java - 如何仅在特定方法中使用 RESTEasy PreProcessInterceptor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11370107/