第一步:下载所需要的架包,下载位置: 链接: https://pan.baidu.com/s/1-_fgFqlSxjdcYS_YXOJh9g 密码: qaax
第二步:创建动态网站项目,引入架包,如下图所示:
第三步:编写代码:
package sample.hello.resources;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import sample.hello.bean.Address;
import sample.hello.bean.Contact;
import sample.hello.storage.ContactStore;
@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;
}
@GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public String getCount() {
int count = ContactStore.getStore().size();
return String.valueOf(count);
}
@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");
}
@Path("{contact}")
public ContactResource getContact(
@PathParam("contact") String contact) {
return new ContactResource(uriInfo, request, contact);
}
}
package sample.hello.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class HelloResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
return "Hello Jersey";
}
}
package sample.hello.resources;
import java.util.ArrayList;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import sample.hello.bean.Address;
import sample.hello.bean.Contact;
import sample.hello.storage.ContactStore;
import sample.hello.util.ParamUtil;
import com.sun.jersey.api.NotFoundException;
//https://www.ibm.com/developerworks/cn/web/wa-aj-tomcat/#artdownload
public class ContactResource {
@Context
UriInfo uriInfo;
@Context
Request request;
String contact;
public ContactResource(UriInfo uriInfo, Request request, String contact) {
this.uriInfo = uriInfo;
this.request = request;
this.contact = contact;
}
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Contact getContact() {
Contact cont = ContactStore.getStore().get(contact);
if (cont == null)
throw new NotFoundException("No such Contact.");
return cont;
}
@PUT
@Consumes(MediaType.APPLICATION_XML)
public Response putContact(JAXBElement<Contact> jaxbContact) {
Contact c = jaxbContact.getValue();
return putAndGetResponse(c);
}
@PUT
public Response putContact(@Context HttpHeaders herders, byte[] in) {
Map<String, String> params = ParamUtil.parse(new String(in));
Contact c = new Contact(params.get("id"), params.get("name"), new ArrayList<Address>());
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
public void deleteContact() {
Contact c = ContactStore.getStore().remove(contact);
if (c == null)
throw new NotFoundException("No such Contact.");
}
}
package sample.hello.bean;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Contact {
private String id;
private String name;
private List<Address> addresses;
public Contact() {}
public Contact(String id, String name, List<Address> addresses) {
this.id = id;
this.name = name;
this.addresses = addresses;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name="address")
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
}
package sample.hello.bean;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Address {
private String city;
private String street;
public Address() {}
public Address(String city, String street) {
this.city = city;
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
package sample.hello.storage;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import sample.hello.bean.Address;
import sample.hello.bean.Contact;
public class ContactStore {
private static Map<String, Contact> store;
private static ContactStore instance = null;
private ContactStore() {
store = new HashMap<String, Contact>();
initOneContact();
}
public static Map<String, Contact> getStore() {
if (instance == null) {
instance = new ContactStore();
}
return store;
}
private static void initOneContact() {
Address[] addrs = { new Address("Shanghai", "Long Hua Street"), new Address("Shanghai", "Dong Quan Street") };
Contact cHuang = new Contact("huangyim", "Huang Yi Ming", Arrays.asList(addrs));
store.put(cHuang.getId(), cHuang);
}
}
package sample.hello.util;
import java.util.HashMap;
import java.util.Map;
public class ParamUtil {
public static Map<String,String> parse(String paramString) {
Map<String,String> params = new HashMap<String,String>();
String[] paramPairs = paramString.split("&");
for(String param : paramPairs) {
String[] key_value = param.split("=");
params.put(key_value[0], key_value[1]);
}
return params;
}
}
package sample.hello.client;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;
import sample.hello.bean.Address;
import sample.hello.bean.Contact;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.representation.Form;
public class ContactClient {
public static void main(String[] args) {
Client c = Client.create();
//WebResource r = c.resource("http://localhost:8080/Jersey/rest/contacts");
WebResource r = c.resource("http://localhost/samplehello/rest/hello");
System.out.println("===== Get huangyim =====");
getOneContact(r, "huangyim");
System.out.println("===== Create foo =====");
postForm(r, "foo", "bar");
Address[] addrs = {
new Address("Shanghai", "Ke Yuan Street")
};
Contact cnt = new Contact("guoqing", "Guo Qing", Arrays.asList(addrs));
System.out.println("===== Create guoqing =====");
putOneContact(r, cnt);
System.out.println("===== All Contacts =====");
getContacts(r);
System.out.println("===== Delete foo =====");
deleteOneContact(r, "foo");
System.out.println("===== All Contacts =====");
getContacts(r);
}
public static void getContacts(WebResource r) {
// 1, get response as plain text
String jsonRes = r.accept(MediaType.APPLICATION_JSON).get(String.class);
System.out.println(jsonRes);
String xmlRes = r.accept(MediaType.APPLICATION_XML).get(String.class);
System.out.println(xmlRes);
// 2, get response and headers etc, wrapped in ClientResponse
ClientResponse response = r.get(ClientResponse.class);
System.out.println( response.getStatus() );
System.out.println( response.getHeaders().get("Content-Type") );
String entity = response.getEntity(String.class);
System.out.println(entity);
// 3, get JAXB response
GenericType<List<Contact>> genericType = new GenericType<List<Contact>>() {};
List<Contact> contacts = r.accept(MediaType.APPLICATION_XML).get(genericType);
System.out.println("No. of Contacts: " + contacts.size());
Contact contact = contacts.get(0);
System.out.println(contact.getId() + ": " + contact.getName());
}
public static void getOneContact(WebResource r, String id) {
GenericType<JAXBElement<Contact>> generic = new GenericType<JAXBElement<Contact>>() {};
JAXBElement<Contact> jaxbContact = r.path(id).accept(MediaType.APPLICATION_XML).get(generic);
Contact contact = jaxbContact.getValue();
System.out.println(contact.getId() + ": " + contact.getName());
}
public static void postForm(WebResource r, String id, String name) {
Form form = new Form();
form.add("id", id);
form.add("name", name);
ClientResponse response = r.type(MediaType.APPLICATION_FORM_URLENCODED)
.post(ClientResponse.class, form);
System.out.println(response.getEntity(String.class));
}
public static void putOneContact(WebResource r, Contact c) {
ClientResponse response = r.path(c.getId()).accept(MediaType.APPLICATION_XML)
.put(ClientResponse.class, c);
System.out.println(response.getStatus());
}
public static void deleteOneContact(WebResource r, String id) {
ClientResponse response = r.path(id).delete(ClientResponse.class);
System.out.println(response.getStatus());
}
}
第四步:测试结果,上面的代码调试通过之后,用tomcat部署项目,项目部署完成之后使用postman或者其他测试工具都可以,本人使用postman测试,例如我们要测试sayHello()这个接口,请求方式:get,输入请求地址:http://localhost/samplehello/rest/hello,点击发送:Send,如下图结果
第五步:项目下载地址:链接: https://pan.baidu.com/s/1yc-rV5WEAKoEFztdEcalhQ 密码: rcy9