新澤西提供兩類資源與註釋交互:我怎樣才能獲得資源的註釋在新澤西ContainerResponseFilter
- ResourceFilterFactory,一個類可以繼承它在應用程序啓動 一次被觸發
- ContainerRequestFilter,ContainerResponseFilter,幾類可以繼承他們爲每個請求/響應觸發
ResourceFilterFacto ry定義了一個create
方法(執行),該方法採用AbstractMethod
,該方法可以訪問方法和類註解。
ContainerRequestFilter和ContainerResponseFilter定義了一個filter
接受請求/響應的方法(實現),但是這些方法只能訪問被調用的方法註釋,而不是一級。
我想實現一個CacheControl註釋,它定義了HTTP緩存頭以下面的方式。
@Path("/path")
@CacheControl(maxAge = 172800)
public class Resource
{
@GET
@Path("/{id}")
@CacheControl(mustRevalidate = true)
public Response get(@PathParam("id") Long id)
{
...
}
}
我的問題是,我不希望爲我的應用程序定義的每個REST方法的新CacheControlFilter。
public class FilterFactory implements ResourceFilterFactory
{
@Override
public List<ResourceFilter> create(AbstractMethod method)
{
List<ResourceFilter> filters = newArrayList();
if (isAnnotationPresent(method, CacheControl.class))
filters.add(new CacheControlFilter(method));
return filters;
}
private boolean isAnnotationPresent(AbstractMethod method, Class<? extends Annotation> clazz)
{
return method.isAnnotationPresent(clazz) || method.getResource().isAnnotationPresent(clazz);
}
}
是否有訪問AbstractMethod
沒有實例化一個CacheContronlFilter每一個REST方法的方法嗎?
public class CacheControlFilter implements ResourceFilter, ContainerResponseFilter
{
private AbstractMethod method;
public CacheControlFilter(AbstractMethod method)
{
this.method = method;
}
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response)
{
putCacheControlIfExists(response, method.getAnnotations());
putCacheControlIfExists(response, method.getResource().getAnnotations());
return response;
}
private void putCacheControlIfExists(ContainerResponse response, Annotation[] annotations)
{
CacheControl annotation = findCacheControl(annotations);
if (annotation != null)
response.getHttpHeaders().put(CACHE_CONTROL, createCacheControlHeader(annotation));
}
private CacheControl findCacheControl(Annotation[] annotations)
{
for (Annotation annotation : annotations)
if (annotation instanceof CacheControl)
return (CacheControl) annotation;
return null;
}
private List<Object> createCacheControlHeader(CacheControl annotation)
{
javax.ws.rs.core.CacheControl header = new javax.ws.rs.core.CacheControl();
header.setMaxAge(annotation.maxAge());
header.setMustRevalidate(annotation.mustRevalidate());
header.setNoCache(annotation.noCache());
header.setNoStore(annotation.noStore());
header.setNoTransform(annotation.noTransform());
header.setProxyRevalidate(annotation.proxyRevalidate());
return Lists.<Object> newArrayList(Splitter.on(',').split(header.toString()));
}
@Override
public ContainerRequestFilter getRequestFilter()
{
return null;
}
@Override
public ContainerResponseFilter getResponseFilter()
{
return this;
}
}
共享實例是我需要的軌道;) –