私はjax-rsサービス内でインターセプタ(カスタムアノテーション)を使いたいと思っていました。JAX-RSインターセプタは動作しません
1.Firstは、私は、アノテーションクラスを書いた: BasicAuthentication.java:
@NameBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BasicAuthentication {
}
2.Then私はBasicAuthenticationInterceptorが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 /テスト/ 1を要求するたびに、私は正しい応答を得ることができ、インターセプタは全く動作しないようです。
私はWildfly 10を使用しています。 ありがとうございます。