Restful入门实战演练
由于工作需要,研究了一下Rest.
1.创建web应用,加入如下jar包。

2.创建Student实体
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="student")
public class Student {
private int id;
private String name;
public Student(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
3.创建Resource
import java.util.Iterator;
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 org.codehaus.jackson.map.deser.FromStringDeserializer;
import org.restlet.data.Form;
import org.restlet.data.Parameter;
import org.restlet.representation.Representation;
@Path("student")
public class StudentResource {
@GET
@Path("{id}/xml")
@Produces("application/xml")
public Student getStudentXml(@PathParam("id") int id) {
//路径为http://localhost:8085/student/1/xml
return ResourceServer.getDefaultStudent();
}
@GET
@Path("{id}/json")
@Produces("application/json")
public Student getStudentJson(@PathParam("id") int id) {
//路径为http://localhost:8085/student/1/json
return ResourceServer.findStudent(id);
}
@GET
@Path("delete/{name}")
public void delete(@PathParam("name") String name){
//路径为http://localhost:8085/student/delete/小王
System.out.println("和数据库交互,删除name 为"+name +"的student");
}
@POST
@Path("update")
public void update(Representation data){
//form表单通过Post将数据传过来。路径为http://localhost:8085/student/update/+form数据
Form form =new Form(data);
Iterator<Parameter> it =form.iterator();
Student stu =new Student();
while(it .hasNext()){
Parameter p =it.next();
String key =p.getName();
String val =p.getValue();
if("id".equals(key)){
stu.setId(Integer.parseInt(val));
}else if("name".equals(key)) {
stu.setName(val);
}
}
// 将student加入到数据库。
}
}
4 .创建Application
public class StudentApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> rrcs = new HashSet<Class<?>>();
rrcs.add(StudentResource.class);
return rrcs;
}
}
5 创建Server 类,该类启动rest服务。
public class Server {
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8085);
component.getDefaultHost().attach(new StudentApplication (new Context()));
component.start();
}
}
启动该类,rest服务就被绑定在了8085端口。
<!--StartFragment -->
查看: http://localhost:8085/student/1/xml

http://localhost:8085/student/1/json

其他功能以此类推。
实例项目提供下载。