java - 在 ReSTLet 中检索资源 ID

标签 java rest web restlet

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?

最佳答案

如果您在附加服务器资源时定义了路径参数,则可以使用方法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"
    }
}

希望对你有帮助, 蒂埃里

关于java - 在 ReSTLet 中检索资源 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29410258/

相关文章:

java - 将 Java Map 的条目打印为表格的有效方法?

web-services - 将 restful 架构映射到 CRUD 功能

rest - Angular 2 http post 返回 200 但没有返回响应

javascript - 下面的代码如何防止XSS?

java - Android 分发包含后台服务的 SDK。

java - JPA 2.0 在刷新操作时从映射父类(super class)继承空字段

javascript - 类型错误 : Failed to construct 'PasswordCredential' : 'id' must not be empty

javascript - 在 Angular2 中实现基于角色的访问

java - 使用java在环形平面上包含/排除

rest - ASP.NET Web API 设计的最佳实践?