2

我想根据调用的方法不同地授权对我的 rest api 的调用。但RequestHandler看起来像这样:

public interface RequestHandler {

    Response handleRequest(Message m, 
                           ClassResourceInfo resourceClass);

}

我不知道如何Method从 that 中调用 that resourceClass。这可能吗?

ResponseHandler似乎有一个可以执行此操作的参数,名为OperationResourceInfo

public interface ResponseHandler {
    Response handleResponse(Message m,
                            OperationResourceInfo ori,
                            Response response);
}

但是到那时,我已经删除了我无权删除的东西(例如)。

如何确定在请求过滤器中将调用什么方法?FWIW,我想要的原因Method是因为我想搜索我将放在每个方法上的自定义构建注释。如果有更好的方法来解决这个问题,我对这个想法持开放态度。


为了完整起见,这里是有关该主题的文档: http: //cxf.apache.org/docs/jax-rs-filters.html

4

1 回答 1

1

您可以使用拦截器,而不是RequestHandler过滤器,因为在 JAXRS 2.0 中不推荐使用请求处理程序并将其替换为ContainerRequestFilterContainerResponseFilter

例如

假设我有如下所示的 RestService

@Service
@Path("/Course")
public class KPRestService {

    private final Logger LOG = LoggerFactory.getLogger(KPRestService.class);

    @POST
    @Path("/create")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response create(CourseType course){
        LOG.info("You have selected {}", course.getCName());
        return Response.ok().build();
    }

    @POST
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public CourseType get(@FormParam("cDate")Date date){

        final CourseType course = new CourseType();
        if(date.after(new Date())){
            course.setCName("E&C");
            course.setCDuration(4);
        }else{
            course.setCName("Mech");
            course.setCDuration(3);
        }

        return course;
    }

}

我阻止使用拦截器调用 get 方法,如下所示。

@Component
public class KPFilter extends AbstractPhaseInterceptor<Message> {

    private final static Logger LOG = LoggerFactory.getLogger(KPFilter.class);

    public KPFilter() {
        super(Phase.PRE_LOGICAL);

    }

    public void handleMessage(Message message) throws Fault {

        final Exchange exchange = message.getExchange();

        exchange.put(Message.REST_MESSAGE, Boolean.TRUE);
        OperationResourceInfo resourceInfo = exchange.get(OperationResourceInfo.class);
        LOG.info("Method name is {}", resourceInfo.getMethodToInvoke().getName());
        if (resourceInfo != null && resourceInfo.getMethodToInvoke().getName().equals("get")) {
            Response response = Response.status(Response.Status.FORBIDDEN).entity("You are not authorised")
                    .type(MediaType.TEXT_XML).build();
            exchange.put(Response.class, response);
        }

    }

}
于 2015-04-15T09:51:39.227 回答