如何@NameBinding在Jersey中使用过滤器对特定资源方法或资源类应用过滤器?
请考虑以下注释:
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface SomeAnnotaion{}
Run Code Online (Sandbox Code Playgroud)
它是如何工作的?
cas*_*lin 32
名称绑定是一种概念,它允许向JAX-RS运行时说明仅针对特定资源方法执行特定过滤器或拦截器.当过滤器或拦截器仅限于特定的资源方法时,我们说它是名称绑定的.没有这种限制的过滤器和拦截器称为全局.
可以使用@NameBinding注释将过滤器或拦截器分配给资源方法.此批注用作其他用户实现的批注的元标注,这些批注应用于提供者和资源方法.请参阅以下示例:
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Compress {}
Run Code Online (Sandbox Code Playgroud)
上面的示例定义了一个新的@Compress注释,它是一个注释注释的名称绑定注释@NameBinding.该@Compress注释可用于绑定的过滤器和拦截器到端点.
假设您有一个执行GZIP压缩的拦截器,并且您希望将此类拦截器绑定到资源方法.为此,请注释资源方法和拦截器,如下所示:
@Compress
public class GZIPWriterInterceptor implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context)
throws IOException, WebApplicationException {
final OutputStream outputStream = context.getOutputStream();
context.setOutputStream(new GZIPOutputStream(outputStream));
context.proceed();
}
}
Run Code Online (Sandbox Code Playgroud)
@Path("helloworld")
public class HelloWorldResource {
@GET
@Produces("text/plain")
public String getHello() {
return "Hello World!";
}
@GET
@Path("too-much-data")
@Compress
public String getVeryLongString() {
String str = ... // very long string
return str;
}
}
Run Code Online (Sandbox Code Playgroud)
该@Compress应用的资源的方法getVeryLongString()和拦截器GZIPWriterInterceptor.只有在执行具有此类注释的任何资源方法时,才会执行拦截器.
在上面的示例中,拦截器将仅针对该getVeryLongString()方法执行.不会为方法执行拦截器getHello().在这个例子中,原因可能很清楚.我们想只压缩长数据,我们不需要压缩短响应"Hello World!".
名称绑定可以应用于资源类.在该示例HelloWorldResource中将使用注释@Compress.这意味着在这种情况下所有资源方法都将使用压缩.
请注意,始终执行全局筛选器,因此即使对于具有任何名称绑定注释的资源方法也是如此.
| 归档时间: |
|
| 查看次数: |
10024 次 |
| 最近记录: |