简单的?RESTful Web 服务 ?Jersey编程用例 ? 附代码
?
资源:
?
@Path("/contacts")
public class ContactsResource {
@Context
UriInfo uriInfo;
@Context
Request request;
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Contact> getContacts() {
List<Contact> contacts = >new ArrayList<Contact>();
contacts.addAll( ContactStore.getStore().values() );
return contacts;
}
@Path("{contact}")
public ContactResource getContact(
@PathParam("contact") String contact) {
return new ContactResource(uriInfo, request, contact);
}
}
|
?
方法:
?
POST
?
?
@POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void newContact(
@FormParam("id") String id,
@FormParam("name") String name,
@Context HttpServletResponse servletResponse
) throws IOException {
Contact c = new Contact(id,name,new ArrayList<Address>());
ContactStore.getStore().put(id, c);
URI uri = uriInfo.getAbsolutePathBuilder().path(id).build();
Response.created(uri).build();
servletResponse.sendRedirect("../pages/new_contact.html");
}
|
PUT
?
@PUT
@Consumes(MediaType.APPLICATION_XML)
public Response putContact(JAXBElement<Contact> jaxbContact) {
Contact c = jaxbContact.getValue();
return putAndGetResponse(c);
}
private Response putAndGetResponse(Contact c) {
Response res;
if(ContactStore.getStore().containsKey(c.getId())) {
res = Response.noContent().build();
} else {
res = Response.created(uriInfo.getAbsolutePath()).build();
}
ContactStore.getStore().put(c.getId(), c);
return res;
}
?
?
DELETE
?
?
@DELETE
public void deleteContact() {
Contact c = ContactStore.getStore().remove(contact);
if(c==null)
throw new NotFoundException("No such Contact.");
}
?