2.12. RESTEasy Filters 和 Interceptors
JAX-RS 有两个不同的拦截概念:过滤器和拦截器。过滤器主要用于修改或处理传入和传出请求标头或响应标头。它们在请求和响应处理之前和之后执行。
2.12.1. 服务器端过滤器 复制链接链接已复制到粘贴板!
在服务器端,您有两种不同类型的过滤器:Container RequestFilters 和 ContainerResponseFilters。在调用 JAX-RS 资源方法之前,ContainerRequestFilters 运行。ContainerResponseFilters 在调用 JAX-RS 资源方法后运行。
此外,有两种类型的 ContainerRequestFilters :预匹配和后匹配。预匹配 ContainerRequestFilters 由 @PreMatching 注释指定,并在 JAX-RS 资源方法与传入 HTTP 请求匹配之前执行。匹配后 ContainerRequestFilters 由 @PostMatching 注释指定,并在 JAX-RS 资源方法与传入 HTTP 请求匹配后执行。
预匹配过滤器通常用于修改请求属性,以更改它与特定资源方法的匹配方式,如 strip .xml 并添加 Accept 标头。ContainerRequestFilters 可以通过调用 ContainerRequestContext.abortWith(Response) 来中止请求。例如,如果过滤器实施了自定义身份验证协议,它可能希望中止。
执行资源类方法后,JAX-RS 运行所有 ContainerResponseFilters。通过这些过滤器,您可以在清理并发送到客户端之前修改传出响应。
示例:请求过滤器
public class RoleBasedSecurityFilter implements ContainerRequestFilter {
protected String[] rolesAllowed;
protected boolean denyAll;
protected boolean permitAll;
public RoleBasedSecurityFilter(String[] rolesAllowed, boolean denyAll, boolean permitAll) {
this.rolesAllowed = rolesAllowed;
this.denyAll = denyAll;
this.permitAll = permitAll;
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (denyAll) {
requestContext.abortWith(Response.status(403).entity("Access forbidden: role not allowed").build());
return;
}
if (permitAll) return;
if (rolesAllowed != null) {
SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class);
if (context != null) {
for (String role : rolesAllowed) {
if (context.isUserInRole(role)) return;
}
requestContext.abortWith(Response.status(403).entity("Access forbidden: role not allowed").build());
return;
}
}
return;
}
}
示例:Response Filter
public class CacheControlFilter implements ContainerResponseFilter {
private int maxAge;
public CacheControlFilter(int maxAge) {
this.maxAge = maxAge;
}
public void filter(ContainerRequestContext req, ContainerResponseContext res)
throws IOException {
if (req.getMethod().equals("GET")) {
CacheControl cc = new CacheControl();
cc.setMaxAge(this.maxAge);
res.getHeaders().add("Cache-Control", cc);
}
}
}