pul*_*ulu 8 java rest interceptor resteasy
我正在编写REST API,使用RestEasy 2.3.4.Final.我知道拦截器将拦截我的所有请求,并且PreProcessInterceptor将是第一个(在所有事情之前)被调用.我想知道如何在调用特定方法时调用此Interceptor.
我试图使用PreProcessInterceptor和AcceptedByMethod,但我无法读取我需要的参数.例如,我只需要在调用此方法时运行我的Interceptor:
@GET
@Produces("application/json;charset=UTF8")
@Interceptors(MyInterceptor.class)
public List<City> listByName(@QueryParam("name") String name) {...}
Run Code Online (Sandbox Code Playgroud)
更具体地说,我需要在所有具有a的方法中运行我的拦截器 @QueryParam("name")
在它的签名上,这样我就可以抓住名字并在所有事情之前做点什么.
可能吗?我试图在Interceptor中捕获"name"参数,但我无法做到这一点.
有人可以帮帮我吗?
您可以AcceptedByMethod按照RESTEasy文档中的说明使用
创建一个实现两者PreProcessInterceptor和的类AcceptedByMethod.在accept-method中,您可以检查方法是否具有带注释的参数@QueryParam("name").如果方法具有该注释,则从accept-method 返回true .
在preProcess-method中,您可以从中获取查询参数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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13185 次 |
| 最近记录: |