restfull环境搭建-helloword(三)

原文地址:http://only81.iteye.com/blog/1689537

This section creates a CRUD (Create, Read, Update, Delete) restful web service. It will allow to maintain a list of todos in your web application via HTTP calls.

本章,将调用restful的get,post,delete等相关的操作

首先创建一个bean类,Person类,代码如下:

package sample.hello.resources.bean;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
private String id;
private String name;
private String birthday; public Person() {
} public Person(String id, String name, String birthday) {
this.id = id;
this.name = name;
this.birthday = birthday;
} 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;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
} }

第二步,创建Person的工厂(单例模式),用户person对象的创建、删除和更新等操作:

package sample.hello.resources.bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; public class PersonFactory {
/**
* 单例模式
*/
private static PersonFactory personFactory = null;
private PersonFactory(){}
public static PersonFactory getInstance(){
if(personFactory==null){
personFactory = new PersonFactory();
}
return personFactory;
}
/**
* 存储person的map
*/
private static Map<String, Person>personProvider = new HashMap<String, Person>(); static{
Person person = new Person();
person.setId("111");
person.setName("小敏");
person.setBirthday("1988-03-21");
personProvider.put("111", person); Person person2 = new Person();
person2.setId("222");
person2.setName("小丰");
person2.setBirthday("1988-04-22");
personProvider.put("222", person2);
}
/**
* 根据id获取对应的person
* @param id
* @return
*/
public Person getPersonById(String id){
return personProvider.get(id);
}
/**
* 添加对应的person到map中
* @param person
*/
public void addPerson(Person person){
personProvider.put(person.getId(), person);
}
/**
* 删除对应的person
* @param id
*/
public void deletePerson(String id){
personProvider.remove(id);
}
/**
* 获取所有的person
* @return
*/
public List<Person>getAllPerson(){
List<Person> persons = new ArrayList<Person>();
Set<String> keys = personProvider.keySet();
for(String key:keys){
persons.add(personProvider.get(key));
}
return persons;
}
}

第三步,创建personResource,并实现相关person的增、删、改操作

package sample.hello.resources;

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.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.resources.bean.Person;
import sample.hello.resources.bean.PersonFactory; public class PersonResource { @Context
UriInfo uriInfo;
@Context
Request request;
String id;
public PersonResource(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
} @GET
@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
public Person getPerson(){
Person person = PersonFactory.getInstance().getPersonById(id);
if(person==null){
throw new RuntimeException("查到不对id="+id+"的person");
}
return person;
} @GET
@Produces({MediaType.TEXT_XML})
public Person getPersonXML(){
Person person = PersonFactory.getInstance().getPersonById(id);
if(person==null){
throw new RuntimeException("查到不对id="+id+"的person");
}
return person;
} @PUT
@Consumes(MediaType.APPLICATION_XML)
public Response addPerson(JAXBElement<Person>person){
Person per = person.getValue();
return putAndGetResponse(per);
} @DELETE
public void deletePerson(){
Person person = PersonFactory.getInstance().getPersonById(id);
if(person==null){
throw new RuntimeException("Delete: person with " + id + " not found");
}else{
PersonFactory.getInstance().deletePerson(id);
}
} private Response putAndGetResponse(Person person){
Response res;
if(PersonFactory.getInstance().getPersonById(person.getId())!=null){
res = Response.noContent().build();
}else{
res = Response.created(uriInfo.getAbsolutePath()).build();
}
PersonFactory.getInstance().addPerson(person);
return res;
} }

第四步,实现personsResource,实现批量查看,查看数量等操作

package sample.hello.resources;

import java.io.IOException;
import java.util.List; 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.UriInfo;
import javax.servlet.http.HttpServletResponse; import sample.hello.resources.bean.Person;
import sample.hello.resources.bean.PersonFactory; @Path("/persons")
public class PersonsResource { @Context
UriInfo uriInfo;
@Context
Request request; @GET
@Produces(MediaType.TEXT_XML)
public List<Person> getPersonBrowser() {
List<Person> persons = PersonFactory.getInstance().getAllPerson();
return persons;
} @GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public List<Person> getPersons() {
List<Person> persons = PersonFactory.getInstance().getAllPerson();
return persons;
} @GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public String getCount() {
int count = PersonFactory.getInstance().getAllPerson().size();
return String.valueOf(count);
} @POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void newPerson(@FormParam("id") String id,
@FormParam("name") String name,
@FormParam("birthday") String birthday,
@Context HttpServletResponse servletResponse) throws IOException {
Person person = new Person(id,name,birthday); PersonFactory.getInstance().addPerson(person); servletResponse.sendRedirect("../create_person.html");
} @Path("{person}")
public PersonResource getPerson(@PathParam("person") String id) {
return new PersonResource(uriInfo, request, id);
}
}

创建一个html文件,create_person.html,用户返回html格式数据

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form to create a new resource</title>
</head>
<body>
<form action="../de.vogella.jersey.todo/rest/todos" method="POST">
<label for="id">ID</label>
<input name="id" />
<br/>
<label for="name">Summary</label>
<input name="name" />
<br/>
"birthday":
<TEXTAREA NAME="birthday" COLS=40 ROWS=6></TEXTAREA>
<br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>

至此,服务端代码完毕。

最后,编写客户端程序,验证相关的功能,代码如下:

package sample.hello.resources.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder; import sample.hello.resources.bean.Person; import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form; public class PersonsTest { public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI()); Person person = new Person("333","小杜","1988-09-25");
ClientResponse response = service.path("rest").path("persons").path(person.getId()).accept(MediaType.APPLICATION_XML).put(ClientResponse.class,person);
System.out.println(response.getStatus()); System.out.println( service.path("rest").path("persons").accept(MediaType.TEXT_XML).get(String.class));
System.out.println( service.path("rest").path("persons").accept(MediaType.APPLICATION_JSON).get(String.class));
System.out.println( service.path("rest").path("persons").accept(MediaType.APPLICATION_XML).get(String.class)); System.out.println(service.path("rest").path("persons/111").accept(MediaType.APPLICATION_XML).get(String.class));
service.path("rest").path("persons/111").delete(); System.out.println(service.path("rest").path("persons").accept(MediaType.APPLICATION_XML).get(String.class)); Form form = new Form();
form.add("id", "444");
form.add("name", "小飞");
form.add("birthday", "1987-01-03");
response = service.path("rest").path("persons").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class,form);
System.out.println("Form response " + response.getEntity(String.class));
System.out.println(service.path("rest").path("persons").accept(MediaType.APPLICATION_XML).get(String.class)); }
private static URI getBaseURI(){
return UriBuilder.fromUri("http://localhost:8080/Restfull").build();
}
}

运行结果如下图所示:

restfull环境搭建-helloword(三)

至此,restful完整的CRUD操作,就算完成。

源码:http://pan.baidu.com/s/1kUAVSbX

上一篇:mui底部导航栏切换分页


下一篇:再探jQuery