我看过Jersey的文档,但是对于如何在Jersey中编写嵌套的资源我仍然有些迷茫。
我有一个Person资源,我想为其提供待办事项列表子资源。因此,您可以以个人身份登录并访问以下网址以获取列表:{personId} / Lists / {listId}
@Path("person")
public class PersonRestService {
private PersonDataService dataService = PersonDataService.getInstance();
private ToDoListDataService listDataService = ToDoListDataService.getInstance();
//Omitted code for the Person resource
//Get a list by it's numerical ID number
@GET
@Path("{id}/Lists/{listId}")
public ToDoList getListById(@PathParam("id")String id, @PathParam("listId")String listId)
{
return listDataService.getToDoListById(listId);
}
//Post a new list to the {personId}/Lists URL
@POST
@Path("{personId}/Lists/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String createToDoList(@PathParam("personId")String personId, @PathParam("listId")String listId,ToDoList newList)
{
return listDataService.addToDoList(newList);
}
这是ToDoListDataService:
public class ToDoListDataService {
private static ToDoListDataService ourInstance = new ToDoListDataService();
private List<ToDoList> ToDoLists = new ArrayList<>();
public static ToDoListDataService getInstance()
{
return ourInstance;
}
// Functions for ToDoList
public String addToDoList(ToDoList toDoList)
{
String newListId = Integer.toString(ToDoLists.size() + 1);
toDoList.setId(newListId);
ToDoLists.add(toDoList);
return newListId;
}
public List<ToDoList> getLists()
{
return ToDoLists;
}
public ToDoList getToDoListById(String id)
{
for (ToDoList list: ToDoLists)
{
if(list.getId().equals(id))
{
return list;
}
}
return null;
}
public void deleteToDoListById(String id)
{
for (ToDoList list: ToDoLists)
{
if(list.getId().equals(id))
{
ToDoLists.remove(list);
}
}
}
}
在客户端应用程序中,我将此功能称为:
private static void postToDoList(WebTarget target, String personId, String title)
{
ToDoList list = ClientUtil.createNewList(title);
// Set correct path for the person who wants to create this list
target = target.path(String.valueOf(personId) + "/Lists/" + String.valueOf(list.getId()));
Response response = target.request().accept(MediaType.TEXT_PLAIN_TYPE).post(Entity.json(list));
System.out.println(response);
}
但是当我尝试为已创建的personId创建列表时,出现404 not found错误。这些操作与我创建人员类的方式非常相似,因此我在构造子资源类的方式上一定做错了。
在调用postToDoList之后,我也将null返回到url,但是即使我对其进行硬编码以使用正确的ID,我仍然找不到404。
如果这是一个简单的错误,请提前道歉,这是我第一次与Jersey合作。