有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在Restlet中检索资源id

Restlet与下面的等价物是什么 我在Jersey上使用的代码片段:

  @GET
  @Path("{id}")
  @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,MediaType.TEXT_XML})
  public Todo getEntityXMLOrJSON(@PathParam("id") int id)
  {
    ...
  }

我的意思是,在使用Restlet框架时,我会执行以下操作:

public class ContactsApplication extends Application {
    public Restlet createInboundRoot() {
        Router router = new Router(getContext());
        router.attach("/contacts/{contactId}", ContactServerResource.class);
        return router;
    }
}

如何在get方法中检索contactId


共 (1) 个答案

  1. # 1 楼答案

    如果在附加服务器资源时定义路径参数,则可以使用方法getAttribute访问该服务器资源中的路径参数值,如下所述:

    public class ContactServerResource extends ServerResource {
        @Get
        public Contact getContact() {
            String contactId = getAttribute("contactId");
            (...)
        }
    }
    

    可以注意到,可以将这些元素定义为实例变量。以下代码是服务器资源ContactServerResource的典型实现:

    public class ContactServerResource extends ServerResource {
        private Contact contact;
    
        @Override
        protected void doInit() throws ResourceException {
            String contactId = getAttribute("contactId");
            // Load the contact from backend
            this.contact = (...)
            setExisting(this.contact != null);
        }
    
        @Get
        public Contact getContact() {
            return contact;
        }
    
        @Put
        public void updateContact(Contact contactToUpdate) {
           // Update the contact based on both contactToUpdate
           // and contact (that contains the contact id)
        }
    
        @Delete
        public void deleteContact() {
           // Delete the contact based on the variable "contact"
        }
    }
    

    希望对你有帮助, 蒂埃里