拦截器
这可以通过 拦截器 来实现。
拦截器旨在通过操纵实体输入/输出流来操纵实体。有两种拦截器,
ReaderInterceptor和
WriterInterceptor。
阅读器拦截器用于操纵入站实体流。这些是来自“电线”的流。因此,使用阅读器拦截器,您可以在服务器端操纵请求实体流。编写器拦截器用于将实体写入“线路”的情况,这在服务器上意味着写出响应实体时
以下实现该
ReaderInterceptor接口的拦截器使您可以在服务器端修改请求的实体:
@Providerpublic class CustomReaderInterceptor implements ReaderInterceptor { @Override public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException { InputStream stream = context.getInputStream(); // Manipulate the HTTP entity using the InputStream context.setInputStream(stream); return context.proceed(); }}请注意,上面的拦截器是 global的 ,也就是说,它将对所有资源方法都执行。
使用Jackson时,您的
ReaderInterceptor#aroundReadFrom(ReaderInterceptorContext)方法实现可能类似于:
// Create a Jackson ObjectMapper instance (it can be injected instead)ObjectMapper mapper = new ObjectMapper();// Parse the requested entity into a JSON treeJsonNode tree = mapper.readTree(context.getInputStream());// Add a property to the JSON((ObjectNode) tree).put("field", "value");// Set the input stream containing the manipulated JSONcontext.setInputStream(new ByteArrayInputStream(mapper.writevalueAsBytes(tree)));// Proceed to the next interceptor in the chaincontext.proceed();名称绑定
要仅对某些精选资源方法执行拦截器,可以使用 名称绑定 。
名称绑定 是一个概念,它允许对JAX-RS运行时说,仅针对特定资源方法才执行特定过滤器或拦截器。当过滤器或拦截器仅限于特定资源方法时,我们说它是
名称绑定的 。
可以使用
@NameBinding注释将过滤器分配给资源方法。该批注用作其他用户实施的批注的元批注,这些其他用户实现的批注已应用于提供程序和资源方法。
可以按以下方式定义名称绑定批注(批注的名称取决于您):
@NameBinding@Retention(RUNTIME)@Target({TYPE, METHOD})public @interface CustomizeResponse { }将上面定义的注释放在您的拦截器类上:
@Provider@CustomizeResponsepublic class CustomReaderInterceptor implements ReaderInterceptor { ...}要将拦截器分配给资源方法,请将上面定义的注释放在资源方法上:
@GET@CustomizeResponse@Produces(MediaType.APPLICATION_JSON)public Response myMethod() { ...}名称绑定也可以应用于资源类。这意味着将对该资源类的所有资源方法执行拦截器:
@Path("/foo")@CustomizeResponsepublic class MyResource() { ...}请注意, 始终执行全局过滤器和拦截器 ,因此即使对于具有任何名称绑定批注的资源方法也是如此。
额外资源
有关拦截器的更多详细信息,请参阅Jersey
文档。



