REST 并非旨在处理复杂查询,因为查询实际上是 URL。当您检索资源时,您指定所需资源的 ID。这只是一个数字或字符串,例如很容易在 URL 中表示;
http://host/employee/57
会给你员工 57。如果你的要求更复杂,那么你可能想要使用搜索方法,在其中传递几个参数。您可以@QueryParam
在此处使用,但这并不是真正的纯 REST。
如果您正在 POST 或 PUTting 数据,那么您使用与执行 GET 时相同的 URL,只是这次您在内容正文中发送数据。由于您能够序列化对象以将其返回到 GET 请求,因此您的客户端也应该能够对其进行序列化以在 PUT 或 POST 中将其发送给您。
这是 GET 和 POST 的示例;
@XmlType
public class Employee {
private int id;
private String name;
//getters and setters
}
@Path("/employee")
public class EmployeeService {
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_XML)
public Employee get(@PathParam("id") String id) {
Employee e = employeeDao.getEmployee(id);
if (e != null) {
return e;
} else {
throw new WebApplicationException(404);
}
}
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Employee post(Employee employee) {
return employeeDao.insertEmployee(employee); //Assumes your DAO sets the ID
}
}