我们计划在我们的REST API中使用Jersey的参考实现。作为一个原型工作,我也在使用ContainerRequestFilters,我实现了多个。有没有办法控制这些过滤器的执行顺序?
我在这里考虑的方案是确保安全过滤器必须是第一个运行的过滤器,如果需要,建立SecurityContext然后执行其他过滤器。
答案 0 :(得分:8)
是的,您可以使用javax.annotation.Priority
属性和默认javax.ws.rs.Priorities
来控制此操作。例如,如果你想:
你可以这样做:
@Priority(Integer.MIN_VALUE)
public class CustomLoggingFilter implements ContainerRequestFilter
{
@Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
// DO LOGGING HERE, THIS RUNS FIRST
}
}
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter
{
@Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
String authHeader = requestContext.getHeaderString(HttpHeaders.WWW_AUTHENTICATE);
// DO AUTHENTICATION HERE, THIS RUNS SECOND
}
}
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter
{
@Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
String authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// DO AUTHORIZATION HERE, THIS RUNS THIRD
}
}
@Priority(Priorities.USER)
public class MyAwesomeStuffFilter implements ContainerRequestFilter
{
@Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
// DO AWESOME STUFF HERE, THIS RUNS LAST
}
}