【发布时间】:2014-12-12 05:33:17
【问题描述】:
我正在尝试设计一个简单的 REST API,其中包含一个根资源(用户)和两个子资源(朋友列表和个人资料)。所以我写了这个角色
@Path("users/{username}")
public class UtentiResource
{
private UtenteResource prova;
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response doPost (@PathParam("username") String username , AuthDTO auth)
{
new UtenteService ().registrazione(username, auth.getPassword(), auth.getEmail());
return Response.ok().build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public UtenteResource doGet (@PathParam("username") String username)
{
prova = new UtenteResource (username);
return prova;
}
@Path("amici")
public AmiciResource getAmici ()
{
return prova.getAmiciRes();
}
@Path ("/profile")
public ProfiloResource getProfilo()
{
return prova.getProfiloRes();
}
}
这里是UtenteResource,它代表单个用户并与子资源相关联
public class UtenteResource
{
private String username;
private String profilo;
private String amici;
private ProfiloResource profiloRes;
private AmiciResource amiciRes;
public UtenteResource (String username)
{
this.username = username;
this.profilo = URIs.UTENTE_RES + "/" + username + URIs.PROFILO_SUBRES;
this.amici = URIs.UTENTE_RES + "/" + username + URIs.AMICI_SUBRES;
}
public String getProfilo()
{
return profilo;
}
public String getAmici()
{
return amici;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public ProfiloResource getProfiloRes()
{
return profiloRes;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public AmiciResource getAmiciRes()
{
return amiciRes;
}
我知道,我不应该对 URL 进行硬编码,而是一步一步来!
顺便说一句,这是我在执行 GET /users/abcd 时得到的
{
"username": "abcd",
"profilo": "http://localhost:8084/nice2mit_backend/restAPI/users/abcd/profile",
"amici": "http://localhost:8084/nice2mit_backend/restAPI/users/abcd/amici",
"profiloRes": null,
"amiciRes": null
}
但我不想在我的响应正文中出现“profiloRes”和“amiciRes”,因为我想让他们使用 GET users/abcd/amici 和 GET users/abcd/profile 进行导航
那么,如何制作呢?
【问题讨论】:
-
这里有一个很好的使用子资源的描述,也许它会帮助你找出你遇到的问题:stackoverflow.com/questions/26270706/…
标签: java json rest resources jersey