ContainerRequestFilter和ContainerResponseFilter都在javax.ws.rs.container包下
ContainerRequestFilter 和 ContainerResponseFilter
如果在服务端进行过滤请求(比如认证)可以实现该接口。
默认情况下,实现该接口的类,
- 实现类必须使用
@Provider
注解修饰,这样才会被JAX-Rs执行。(javax.ws.rs.ext.Provider
) - 如果没有使用注解(
javax.ws.rs.NameBinding
),对于该实现类的实例,作用域是全局的。(@NameBinding
在下面讲解) - 如果实现类不使用
@PreMatching
注解,将在请求到资源(该处资源指的是被@Get、@Post、@Put…修饰的方法)之后执行。 - 如果实现类使用
@PreMatching
注解,将在请求到资源之前执行。
例子:
@Provider
@PreMatching
public class CubeCoreFilter implements ContainerRequestFilter,ContainerResponseFilter {
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
CubeContextManager.createContext(containerRequestContext); //存储请求到资源的请求信息
}
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
CubeContextManager.clear(); //清楚存储的信息
}
}
@NameBinding
元注释用于为过滤器和拦截器创建名称绑定注释。
通过@NameBinding
修饰的复合注解,只能在服务端代码中使用
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(value = RetentionPolicy.RUNTIME)
@NameBinding
public @interface Logged { }
然后使用定义的名称绑定注释来修饰过滤器或拦截器类(可以使用相同的名称绑定注释修饰多个过滤器或拦截器)
@Logged
public class LoggingFilter
implements ContainerRequestFilter, ContainerResponseFilter {
//TODO 可以实现记录日志
}
最后,名称绑定注释应用于绑定名称的JAX-RS提供程序应绑定到的资源方法:
@Path("/")
public class MyResourceClass {
@GET
@Produces("text/plain")
@Path("{name}")
@Logged
public String hello(@PathParam("name") String name) {
return "Hello " + name;
}
}
名称绑定注释也可以附加到自定义JAX-RS {@link javax.ws.rs.core.Application}子类。在这种情况下,由注释绑定的名称绑定JAX-RS提供程序将应用于JAX-RS应用程序中的所有{@link HttpMethod资源和子资源方法}:
@Logged
@ApplicationPath("myApp")
public class MyApplication extends javax.ws.rs.core.Application {
...
}