如何仅在特定方法中使用RESTEasy PreProcessInterceptor?

时间:2012-07-06 21:49:41

标签: java rest resteasy interceptor

我正在编写REST API,使用RestEasy 2.3.4.Final。 我知道拦截器将拦截我的所有请求,并且PreProcessInterceptor将是第一个(在所有事情之前)被调用。我想知道如何在调用特定方法时调用此Interceptor。

我尝试使用PreProcessInterceptor和AcceptedByMethod,但我无法读取我需要的参数。 例如,我只需要在调用此方法时运行我的拦截器:

@GET
@Produces("application/json;charset=UTF8")
@Interceptors(MyInterceptor.class)
public List<City> listByName(@QueryParam("name") String name) {...}

更具体地说,我需要在所有具有@QueryParam("name")

的方法中运行我的拦截器

在其签名上,以便我可以抓住名称并在所有事情之前做点什么。

有可能吗?我试图在Interceptor中捕获“name”参数,但我无法做到。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:7)

您可以按照RESTEasy documentation

中的说明使用AcceptedByMethod

创建一个同时实现PreProcessInterceptorAcceptedByMethod的类。在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());
    }
}

答案 1 :(得分:2)

如果您返回return new ServerResponse(responseText, 200, new Headers<Object>());,您将失去终点。如果您仍希望将消息传递到最终点,则需要返回null