当前位置: 代码迷 >> Web前端 >> RESTful Web 服务 Jersey运用
  详细解决方案

RESTful Web 服务 Jersey运用

热度:711   发布时间:2012-10-10 13:58:11.0
RESTful Web 服务 Jersey使用

简单的?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.");
}

?

  相关解决方案