如何在jax-rs'ContainerRequestFilter中获取资源方法注释

时间:2017-01-16 06:47:24

标签: java rest permissions jax-rs cxf

我编写了一个扩展ContainerRequestFilter的类来进行权限检查。如何获取匹配方法的注释以进行权限检查。

@javax.ws.rs.ext.Provider
public class AuthorizationRequestFilter implements ContainerRequestFilter {
    public void filter(ContainerRequestContext requestContext) throws IOException {
    // how can I get resources' methods' annotation here? 
    // from the resource below , I want to checkout whether the target matched method contains the @ReadPermission annotation
    }
}

@Path("/region")
public class Region {
   @POST
   @Path("/{region_id}")
   @Produces({MediaType.APPLICATION_JSON , MediaType.APPLICATION_XML})
   @ReadPermission
   public String getRegion() {
      return null;
   }
}

1 个答案:

答案 0 :(得分:3)

您可以使用以下代码(特定于CXF):

 public ActionResult AddTask (TaskModel t, HttpPostedFileBase file)
    {
        if (Session["UserID"] != null)
        {
            using (ToDoListEntities3 context = new ToDoListEntities3())
            {
                FilesTable ff = new FilesTable();


                t.fileId = Convert.ToInt32(Session["UserID"]);

                ff.FileId = t.fileId;

                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);
                    ff.FileName = fileName;

                    var content = new byte[file.ContentLength];
                    file.InputStream.Read(content, 0, file.ContentLength);
                    ff.File = content;


                }

或者这个(JAX-RS的通用)

 public class AuthorizationRequestFilter implements ContainerRequestFilter {
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Message message = JAXRSUtils.getCurrentMessage();
        OperationResourceInfo operation = message.getExchange().get(OperationResourceInfo.class);
        Method m = operation.getMethodToInvoke();
        boolean hasAnnotation =  m.getAnnotation(ReadPermission.class) != null;
    }
}