【问题标题】:JAX-RS interceptor cannot workJAX-RS 拦截器无法工作
【发布时间】:2018-04-30 23:21:04
【问题描述】:

我想在 jax-rs 服务中使用拦截器(自定义注释)。

1.首先,我写了一个注解类: BasicAuthentication.java:

@NameBinding
@Target( {ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BasicAuthentication {
}

2.然后我添加了BasicAuthenticationInterceptor implements javax.ws.rs.ext.ReaderInterceptor

BasicAuthenticationInterceptor.java:

@Provider
@Priority(Priorities.AUTHENTICATION)
@BasicAuthentication

public class BasicAuthenticationInterceptor extends Dumpable implements ReaderInterceptor {

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
        //log.info("authentication here")
        String authHeader = context.getHeaders().getFirst(AUTHORIZATION);
        if (authHeader == null) {
            error("\"authorization\" is not found from the request header.");
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        }
        return  context.proceed();
    }
}

3.最后,我添加了一个带有@BasicAuthentication注解的测试服务。

TestRestfulService.java

@Stateless
@Path("/api")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
@BasicAuthentication
public class TestRestfulService extends Dumpable{
@EJB
LocalService localService;

@Path("/test/{id}")
@GET
public Response test(@PathParam("id")String id) {
try {
    localService.findUser(id);
} catch (Exception e) {
    error(e);
    return Response.serverError().build();
}
return Response.ok().build();
}
}

但是每次我用空头请求 /api/test/1 时,我都能得到正确的响应,拦截器似乎根本不起作用。

我正在使用 Wildfly 10。 提前致谢。

【问题讨论】:

    标签: java jax-rs interceptor


    【解决方案1】:

    终于搞定了。把拦截器改成过滤器:

    public class BasicAuthenticationInterceptor implements javax.ws.rs.container.ContainerRequestFilter {
        @Override
        public void filter(ContainerRequestContext context){
            ...
        }
    }
    

    然后它按预期工作。

    表单 JAX-WS API:

    消息正文阅读器拦截器的接口,它围绕对 MessageBodyReader.readFrom(java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core. MediaType、javax.ws.rs.core.MultivaluedMap、java.io.InputStream)。

    javax.ws.rs.ReaderInterceptor

    这可能是原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-06
      • 2014-03-25
      • 2016-12-08
      • 2011-08-12
      • 2016-03-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      相关资源
      最近更新 更多