由于工作需要,研究了一下Rest.
1.创建web应用,加入如下jar包。
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 + "]"; } |
import java.util.Iterator; import javax.ws.rs.GET; import org.codehaus.jackson.map.deser.FromStringDeserializer; @Path("student") //路径为http://localhost:8085/student/1/xml //路径为http://localhost:8085/student/1/json //路径为http://localhost:8085/student/delete/小王 } |
4 .创建Application
public class StudentApplication extends Application { @Override |
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/json
其他功能以此类推。
实例项目提供下载。